您的位置:首页 > 移动开发 > Unity3D

Unity 3D协程

2018-01-08 23:36 190 查看
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#语言开发跨平台
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Unity 3D 协程