2013-10-07 22 views
2

我有一個關於在循環的情況下,協同程序行爲的問題,請參見下面的代碼提取物例如在統一C#腳本來完成:循環使用協同程序

void Start() { 
    StartCoroutine(FSM()); 
} 

IEnumerator FSM() { 
    state="State1"; 
    while (true) { 
     Debug.Log("State "+state); 
     yield return StartCoroutine(state); 
    } 
} 

IEnumerator State1() { 
    while (true) { 
     if (stateTransitionCond) { 
      state = "NextState"; 
      yield break; 
     } 
     yield return null; 
    } 
} 

狀態機工作正常,但在當前狀態爲狀態1(stateTransitionCond==false),由於在State1()例程的循環內的yield return null,我期待在FMS()內的循環也執行另一個迭代生成調試日誌'Debug.Log(「State」+ state);'。

換句話說,我期待着很多的調試日誌(當狀態爲Status1時,每次執行一次State1()例程),但實際上狀態爲Status1時只執行1次執行。

所以我想我錯過了關於良率功能的東西,有沒有人可以解釋我這種行爲?

+1

的統一標記是微軟統一。不要濫用它。 –

回答

2

您的問題源於這樣的事實,即您的代碼不會突破State1()方法,直到stateTransitionCond == true

直到State1完成,才啓動協程的方法FSM()不會返回。換句話說,在協程完成之前,控制流程不會返回到調用方法。我相信這是因爲你在 -ing State1FSM(產生另一個協程)。顯然,「正常」方法不會等待協程完成,然後繼續執行。

請參閱下面的代碼示例以揭示例如:

using UnityEngine; 
using System.Collections; 

public class CoroutineTest : MonoBehaviour { 
    // current FSM state 
    public string state = ""; 

    void Start() 
    { 
     StartCoroutine(FSM()); 
    } 

    IEnumerator FSM() 
    { 
     state = "State1"; 

     while (true) 
     { 
      Debug.Log("State: " + state); 
      // ExecuteOnce will execute exactly once before returning to the outer function 
      yield return StartCoroutine(ExecuteOnce()); 

      // ExecuteIndefinitely will execute indefinitely until its while() loop is broken 
      // uncomment to test 
      //yield return StartCoroutine(ExecuteIndefinitely()); 
     } 
    } 

    IEnumerator ExecuteOnce() 
    { 
     Debug.Log("Calling ExecuteOnce()"); 
     yield return new WaitForSeconds(1f); 
    } 

    IEnumerator ExecuteIndefinitely() 
    { 
     Debug.Log("Calling ExecuteIndefinitely()"); 
     while (true) 
     { 
      Debug.Log("Inside ExecuteIndefinitely()"); 
      yield return new WaitForSeconds(1f); 
     } 
    } 
}