unity3D是单线程,因此需要协程机制来实现一些类似于多线程的功能,但要明确协程不是进程或线程,其执行过程类似于子例程,或者说不带返回值的函数调用。
- 开启协程
StartCoroutine方法是Mono中定义的一个静态方法,有两个重载版本:
Coroutine StartCoroutine(IEnumerator routine);
Coroutine StartCoroutine(string methonName, Object obj = null);
下面来看简单的例子:
public class ExampleTest : MonoBehaviour {
IEnumerator Start() {
Debug.Log("1.starting..." + Time.time);
yield return StartCoroutine(waitAndPrint(2.0f));
Debug.Log("1.Done...");
Debug.Log("2.starting...");
//开启协程
StartCoroutine("doSomeThing", 2.0f)
yield return new WaitForSeconds(1);
//停止协程
StopCoroutine("doSomeThing");
//StopCoroutine(doSomeThing(2.0f))
}
IEnumerator waitAndPrint(float wait) {
yield return new WaitForSeconds(wait);
Debug.Log("wait and log" + Time.time);
}
IEnumerator doSomeThing(float wait) {
while(true) {
Debug.Log("do some thing" + Time.time);
yield return null;
}
}
}
协程通俗来说其实是使当前逻辑暂停执行,并且将控制权交给unity,但之后还可以从暂停的位置继续执行余下的逻辑。
协程可以使用来实现各种延迟效果,比如:
WaitForSeconds–暂停逻辑等待一段时间继续执行
WaitForFixedUpdate–暂停直至下一次fixUpdate时才会继续执行
WaitForEndOfFrame–等到帧结束再恢复执行逻辑,常用于截屏
2.协程和WWW
通过协程等待www加载完成,然后就可以通过www实例访问下载的内容
下面通过一个综合的例子来说明两者配合使用:
public class HttpWrapper : MonoBehaviour {
public void GET(string url, Action<WWW> onsuccess, Action<WWW> onFail=null) {
WWW www = new WWW(url);
StopCoroutine(WaitForResponse(www, onsuccess, onFail));
}
private IEnumerator WaitForResponse(WWW www, Action<WWW> onsuccess, Action<WWW> onFail=null) {
yield return www;
if(www.error == null) {
onsuccess();
}else{
if(onFail)onFail(www);
}
}
}
public class httpTest : MonoBehaviour {
//无返回值的委托实例
private Action<WWW> onsuccess;
private void Start(){
this.onsuccess += this.successMethod;
HttpWrapper hw = GetComponent<HttpWrapper>;
hw.GET("http://asadad/a.png",this.onsuccess)
}
private successMethod(WWW www) {
if(www == null)
return;
Texture tex = www.texture;
renderer.material.mainTexture = tex;
}
}
3、协程和Async - Await实现异步的区别
这里有详细说明
协程有很广泛的用途,网络上也有各种示例,本篇就到这里了。。。睡觉!