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 ();

猜你喜欢

转载自blog.csdn.net/yuewei19/article/details/78208121