* Credit from http://www.unitygeek.com/coroutines-in-unity3d/
Unity 3D : Corutines
yield return null – Resumes execution after All Update functions have been called, on the next frame
yield return new WaitForSeconds(t) – Resumes execution after (Approximately) t seconds
yield return new WaitForEndOfFrame() – Resumes execution after all cameras and GUI were rendered
yield return new WaitForFixedUpdate() – Resumes execution after all FixedUpdates have been called on all scripts
yield return new WWW(url) – Resumes execution after the web resource at URL was downloaded or failed.
* StopAllCorutines มันจะหยุดเฉพาะ ใน scripts เท่านั้น
using UnityEngine;
using System.Collections;
public class FirstObjectScript : MonoBehaviour {
int a,b;
bool pressed = false;
private IEnumerator coroutineBeginning;
private IEnumerator coroutineSeconding;
// Use this for initialization
void Start () {
coroutineBeginning = Beginning() ;
coroutineSeconding = Seconding() ;
StartCoroutine (coroutineBeginning);
StartCoroutine (coroutineSeconding );
}
public IEnumerator Beginning()
{
while(true)
{
Debug.Log ("In Beginning Before yield return null : " + Time.frameCount );
yield return null;
Debug.Log ("In Beginning After yield return null : " + Time.frameCount );
}
}
public IEnumerator Seconding()
{
while(true)
{
Debug.Log ("In Seconding Before yield return null : " + Time.frameCount );
yield return null;
Debug.Log ("In Seconding After yield return null : " + Time.frameCount );
}
}
// Update is called once per frame
void Update () {
if (pressed == false) {
if (Input.GetKeyDown ("space")) {
pressed = true;
StopAllCoroutines();
}
} else {
if (Input.GetKeyDown ("space")) {
pressed = false;
StartCoroutine (coroutineBeginning);
StartCoroutine (coroutineSeconding);
}
}
}
}
************************************************************
ผลที่ได้
- ก็สมเหตสมผลครับ เริ่มต้นก็ทำงานที่ frame 1 s]
- หลังจากใช้ yield return null ก็ รอจนจบ frame
- หลังจบ frame ก็ขึ้น frame 2
- ในขณะ frame 2 ก็ยังทำงาน ยุ จนกว่าจะมี คำสั่ง yield return ขึ้นมา มัน
จึงจะขึ้น frame ที่ 3 ต่อไป
ไม่มีความคิดเห็น:
แสดงความคิดเห็น