2021-07-24

最近在做一个项目的过程中需要外部对外面与服务器进行一个简单的消息沟通,而对方的服务器采用的是http协议,研究后发现unity有一个专门的类处理,问题是这个在发送消息的时候容易被卡住,因此最好的方式是调用携程的方式,而在处理的过程中需要接收服务器的返回消息,而用全局变量又不是最好的方式,因此考虑到了回调的形式。

携程的申明方式

只需要将原申明上添加一个Action callback的项然后在处理的末尾添加这个函数的调用。如下:
public static IEnumerator Post(int cmdtype, string name, Action callback)
最后一个参数即为回调的申明
IEnumerator Post(int cmdtype, string name, Action callback)
{

if (callback != null) callback();
}

回调函数的申明

这个函数的申明方法与其他函数的申明无异

void overpost()///获取反馈消息
{
    MSG.text = HttpTool.showtxt;
}
如上所示。

调用方法

void OnsendCMD()
{
StartCoroutine(Post(2, “hhhh”, overpost)); //发送消息
}

如果此携程是在其他的类里面申明的这里则需要将携程申明函数前面添加public static关键字,并在StartCoroutine中添加类名
StartCoroutine(htptool.Post(2, “hhhh”, overpost));

以上就是携程添加回调的方式。

猜你喜欢

转载自blog.csdn.net/llhllq2015/article/details/119052374