2017-02-15 75 views
0

我有一個代碼(C#)與更新功能,需要等待幾秒鐘的某個點。問題在於,在執行等待命令時,會繼續執行更新功能,導致應該延遲的位被完全跳過。 由於布爾變量更新只會做這個東西一次,直到我再次可用,所以這是沒有問題的。 這段代碼沒有完全等待,所以不用擔心,我忽略了大多數不需要等待的行。Unity:等待()在更新幾乎工作(但不完全)

void Update() 
{ 

    if (RoundOver == false) 
    { 
     RoundOver = true; 
     Seconds = 3; 
     Debug.Log("Waiting", gameObject); 
     StartCoroutine(Wait()); 
     if (Continue) 
     { 
      Continue = false; 
      Debug.Log("Done Waiting", gameObject); 
      RoundNumber += 1;    //Just game stuff 
      ZombiesLeft = ZombieAmount(); //Just game stuff 
      RoundOver = false; 
     } 
     Debug.Log("Done wit stuff", gameObject); 
    } 
    if (counter > DelayTime && RoundOver == false) 
    { 
     counter = 0; 
     Debug.Log("Going to spawn a zombie", gameObject); 
     SpawnZombie(); 
    } 
    counter += Time.deltaTime; 
    } 

與萊等待功能:

IEnumerator Wait() 
{ 
    Debug.Log("ACTUALLY WAITING", gameObject); 
    yield return new WaitForSeconds(Seconds); 
    Continue = true; 
    Debug.Log("ACTUALLY WAITING DONE", gameObject); 
} 

輸出如下:

Waiting 
ACTUALLY WAITING 
Done wit stuff 
ACTUALLY WAITING DONE 

所以很明顯正確的順序應該是

Waiting 
ACTUALLY WAITING 
ACTUALLY WAITING DONE 
Done wit stuff 

編輯: 的阻止我當滿足(這裏是隱藏的)要求時,if (continue)應該激活第二個塊。第二塊將繼續做它的事情,直到它完成(可能需要幾分鐘),然後再次設置RoundOver爲重新啓用第一個塊。第一個塊基本上是繼續重新運行第二個塊,並增加像RoundNumber +=1這樣的變量,這是唯一的問題,第二個塊間隔3秒。

+0

我已經回答了你的問題,但是如果你告訴我們你想做什麼,因爲我懷疑它不應該進入更新功能 –

+0

更新它在編輯 – RnRoger

+0

你可以通過循環模擬更新與枚舉器並以「WaitForEndOfFrame」結束。所以在你的Start()方法中放入StartCoroutine(IEnumeratorUpdate());然後將您的等待邏輯放在需要代碼的地方! – Maakep

回答

1

我工作圍繞這個轉動void SpawnZombie()成一個IEnumerator,而不必單獨Wait()。然後,我用StartCoroutine(SpawnZombie())替換SpawnZombie()。爲了使它像我想要的那樣行動,我在SpawnZombie()中添加了一個if,以確保僅在需要時等待3秒。

0

你調試語句Debug.Log("Done wit stuff", gameObject);是if語句if (Continue)之外。因此,即使協程仍在運行,它也會顯示。

+0

我明白了,重點在於等待3秒鐘,直到繼續執行代碼。 – RnRoger

1

你不能等待Update函數,你只能等一個返回IEnumerator的函數。

爲此,您可以做出這樣的事情

void Update() 
{ 
    if (RoundOver == false) 
    { 
     RoundOver = true; 
     StartCoroutine(Wait()); 
    } 
    if (counter > DelayTime && RoundOver == false) 
    { 
    counter = 0; 
    Debug.Log("Going to spawn a zombie", gameObject); 
    SpawnZombie(); 
    } 
    counter += Time.deltaTime; 
} 

IEnumerator Wait() 
{ 
    Seconds = 3; 
    Debug.Log("Waiting", gameObject); 
    Debug.Log("ACTUALLY WAITING", gameObject); 
    yield return new WaitForSeconds(Seconds); 
    Debug.Log("Done Waiting", gameObject); 
    RoundNumber += 1;    //Just game stuff 
    ZombiesLeft = ZombieAmount(); //Just game stuff 
    RoundOver = false; 
    Debug.Log("ACTUALLY WAITING DONE", gameObject); 
    Debug.Log("Done wit stuff", gameObject); 
} 

雖然這不是最乾淨的東西,我會從更新刪除如果可能的話所有的代碼,當你需要開始一個協程。

相關問題