Unity3D协程(一)

协程介绍

Unity的协程系统是基于C#的一个简单而强大的接口 ,IEnumerator,它允许你为自己的集合类型编写枚举器。

yield return是“停止执行方法,并且在下一帧从这里重新开始”。

 

简单计时器实例:StartCoroutine()并没有给它传入参数,但是这个方法调用了它自己(这是通过传递CoroutineMethod的return返回值来实现的)

 

	// Use this for initialization
	void Start ()
	{
		StartCoroutine(CoroutineMethod()); 
	}
	
	IEnumerator CoroutineMethod ()
	{
		for (float timer = 3; timer >= 0; timer -= Time.deltaTime) {
			yield return 0;
		}
		Debug.Log ("This message appears after 3 seconds!");  
	}

 

hello实例:

 

	//This will say hello 5 times, once each frame for 5 frames
	IEnumerator SayHelloFiveTimes ()
	{
		yield return 0;
		Debug.Log ("Hello");
		yield return 0;
		Debug.Log ("Hello");
		yield return 0;
		Debug.Log ("Hello");
		yield return 0;
		Debug.Log ("Hello");
		yield return 0;
		Debug.Log ("Hello");
	}

	//This will do the exact same thing as the above function!
	IEnumerator SayHello5Times ()
	{
		for (int i = 0; i < 5; i++) {
			Debug.Log ("Hello");
			yield return 0;
		}
	}

 

 

 

开始和终止协程

 

		//If you start a Coroutine by name...  
		StartCoroutine("FirstTimer");  
		StartCoroutine("SecondTimer");  

		//You can stop it anytime by name!  
		StopCoroutine("FirstTimer");  

		//You can stop all anytime!
		StopAllCoroutines ();

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值