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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章