unity学习笔记-C#协程

unity3D是单线程,因此需要协程机制来实现一些类似于多线程的功能,但要明确协程不是进程或线程,其执行过程类似于子例程,或者说不带返回值的函数调用。

  1. 开启协程
    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实现异步的区别
在这里插入图片描述
这里有详细说明

协程有很广泛的用途,网络上也有各种示例,本篇就到这里了。。。睡觉!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值