close

在使用Unity開發時,會經常使用Coroutine(協程),來做程式流程的結構或當成類似多重執行緒來使用,所以在此列出yield常用的ㄧ些方法,以便日後使用複習

  • yield return null; //下一幀再執行後續程式碼(不消耗內存)
  • yield return 0; //下一幀再執行後續程式碼
  • yield return 任意數字; //下一幀再執行後續程式碼,跟使用yield return 0 一樣
  • yield break; //直接結束該Corotine(協程),跟for-loop(For迴圈)的break一樣功能
  • yield return asyncOperation;//等非同步結束後再執行後續代碼,通常用於加載場景或加載資源
  • yield return StartCoroution(/*某個協程*/);//等待某個Corotine(協程)執行完畢再執行後續程式碼
  • yield return WWW();//等待WWW操作完成後再執行後續程式碼
  • yield return new WaitForEndOfFrame();//等待所有的攝像機和GUI被渲染完成後,在該幀顯示在屏幕之前執行
  • yield return new WaitForSeconds(0.5f);//等待0.5秒,一段指定的時間延遲之後繼續執行,在所有的Update函數調用完的那一幀之後執行(這裏的時間會受到Time.timeScale的影響)
  • yield return new WaitForSecondsRealtime(0.5f);//等待0.5秒,一段指定的時間延遲之後繼續執行,在所有的Update函數調用完的那一幀之後執行(這裏的時間不受到Time.timeScale的影響)
  • yield return WaitForFixedUpdate();//等待下一次FixedUpdate開始時再執行後續程式碼
  • yield return new WaitUntil()//將協程執行直到當輸入的參數(或者委託)為True時,再執行後續程式碼
    public class WaitUntilExample : MonoBehaviour
    {
        public int frame = 0;
    
        void Start()
        {
            StartCoroutine(Example());
        }
    
        IEnumerator Example()
        {       
            Debug.Log("process1...");
            yield return new WaitUntil(() => frame >= 5); 
            Debug.Log("process2...");
        }
    
        void Update()
        {
            if (frame <= 5)
            {           
                Debug.Log("frame is : " + frame);
                frame++;
            }        
        }
    }

  • yield return new WaitWhile()//將協程執行直到當輸入的參數(或者委託)為false時,再執行後續程式碼
    public class WaitWhileExample : MonoBehaviour
    {
        public int frame;
    
        void Start()
        {
            StartCoroutine(Example());
        }
    
        IEnumerator Example()
        {
            Debug.Log("process1...");
            yield return new WaitWhile(() => frame < 5);
            Debug.Log("process2...");
        }
    
        void Update()
        {
            if (frame <= 5)
            {
                Debug.Log("frame is : " + frame);
                frame++;
            }
        }
    }

 

 

arrow
arrow
    文章標籤
    unity教學
    全站熱搜
    創作者介紹
    創作者 c#六角恐龍 的頭像
    c#六角恐龍

    c#六角恐龍的部落格

    c#六角恐龍 發表在 痞客邦 留言(0) 人氣()