Unity 3D协程

Unity3D 是单线程的

StartCoroutine 开启协程
Coroutine StartCoroutine(IEnumerator routine);
Coroutine StartCoroutine(string methodName, object value = null);
yield 暂停协程执行
yield return null  //暂停一帧,然后再执行
StopCoroutine 停止一个协程

StopCoroutine只能停止同一个游戏脚本中的方法名和传入string型参数相同的协程,而无法影响别的脚本中开启的协程,StopCoroutine方法只能用来停止那些使用了StartCoroutine的string型参数的重载版本开启的协程

协程延时效果
  • WaitForSeconds 暂停几秒
  • WaitForFixedUpdate 暂停协程直到下一次FixedUpdate时才会继续
  • WaitForEndOfFrame 等到所有摄像机和GUI被渲染完成后再恢复协程执行
迭代器
  • IEnumerable
//非泛型
public interface IEnumerable
{
  IEnumerator  GetEnumerator();
}

//泛型
public interface IEumerable<out T> :IEumberable
{
  IEnumerator<T> GetEnumerator();
  IEnumerator   GetEnumerator();
}
  • IEnumerator
//非泛型
public interface IEumerator
{
  Object Current {get;}     //当前所指向的值
  bool MoveNext();          //指向下一个结点
  void Reset();
}

//泛型
public interface IEnumerator<out T>: IDisposable, IEnumerator
{
  void Dispose();
  Object Current {get;}        
  T Current {get;}
  bool MoveNext();
  void Reset();
}

迭代器块中的局部变量会被分配到堆上

WWW和协程

WWW类是提供一个用来从提供的URL获取内容的工具类,并且返回该实例来下载URL的内容。WWW类的构造函数除了创建一个新的实例之外,还会创建和发送一个GET请求,并且会自动开启一个流来下载从URL获取内容

使用WWW实现GET请求和POST请求

public class HttpWrapper : MonoBehaviour
{
  public void GET(string url, Action<WWW> onSuccess, Action<WWW> onFail = null)
  {
    WWW www = new WWW(url);
    StartCoroutine(WaitForResponse(www, onSuccess, onFail));
  }

  public void POST(string url, Dictionary<string, string> post, Action<WWW> onSuccess, Action<WWW> onFail)
  {
    WWWForm form = new WWWForm();
    foreach(KeyValuePair<string, string> post_arg in post)
    {
      form.AddField(post_arg.Key, post_arg.Value);
    }
    WWW www = new WWW(url, form);

    StartCoroutine(WaitForResponse(www, onSuccess, onFail));
  }

  private IEumerator WaitForResponse(WWW www, Action<WWW> onSuccess, Action<WWW> onFail = null)
  {
    yield return null;
    if(www.error == null)
    {
      onSuccess(www);
    }
    else
    {
      Debug.LogError("WWW Error");
      if(onFail != null)  onFail(www);
    }
  }
}
参考

Unity 3D脚本编程—-使用c#语言开发跨平台

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值