2016-01-20 131 views
0

我剛開始學習統一的c#。我跟着一個教程,但我想補充一些東西。如何在Unity3D中使用C#進行延遲?

using UnityEngine; 
using UnityEngine.UI; 
using System.Collections; 

public class PlayerController : MonoBehaviour { 

    public float speed; 
    public Text countText; 
    public Text winText; 

    private Rigidbody rb; 
    private int count; 

    void Start() 
    { 
     rb = GetComponent<Rigidbody>(); 
     count = 0; 
     SetCountText(); 
     winText.text = ""; 
    } 

    void FixedUpdate() 
    { 
     float moveHorizontal = Input.GetAxis ("Horizontal"); 
     float moveVertical = Input.GetAxis ("Vertical"); 

     Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical); 

     rb.AddForce (movement * speed); 
    } 

    void OnTriggerEnter(Collider other) 
    { 
     if (other.gameObject.CompareTag ("Pick Up")) 
     { 
      other.gameObject.SetActive (false); 
      count = count + 1; 
      SetCountText(); 
     } 
    } 

    void SetCountText() 
    { 
     countText.text = "Count: " + count.ToString(); 
     if (count >= 1) 
     { 
      winText.text = "You Win!"; 
      Application.LoadLevel(1); 
     } 
    } 

} 

我想在winText.text =「You Win!」之間做一個延遲。 和Application.LoadLevel(1);所以你可以真正閱讀文本。我希望有人能幫助我!

+0

Thread.sleep代碼(50); –

+1

相關:http://stackoverflow.com/q/5449956/3273247 – dbrad

+0

這應該會幫助你 – dbrad

回答

5

使用協程(因爲我看到這是Unity3D代碼):

void OnTriggerEnter(Collider other) 
    { 
     if (other.gameObject.CompareTag ("Pick Up")) 
     { 
      other.gameObject.SetActive (false); 
      count = count + 1; 
      StartCoroutine(SetCountText()); 
     } 
    } 

    IEnumerator SetCountText() 
    { 
     countText.text = "Count: " + count.ToString(); 
     if (count >= 1) 
     { 
      winText.text = "You Win!"; 
      yield return new WaitForSeconds(1f); 
      Application.LoadLevel(1); 
     } 
    } 
+0

在你的回答中指定這種做法完全是針對Unity3D的(完全是正確的做法!) – Falanwe

+0

沒錯,我編輯了這個問題,因爲我認爲命名是錯誤的。 –

+0

感謝它的工作! – FaceMann

0

我可以假設它是一個Windows窗體應用程序,所以你最好不要使用Thread.Sleep,因爲它會阻塞UI線程。

相反,使用: System.Windows.Forms.Timer

+2

這是一個Unity應用程序,所以Windows窗體計時器不是一個真正的選擇,但你說得對'Thread.Sleep'是一個非常確實不好的主意。 – Falanwe

-1

在Unity等待通常與WaitForSeconds類的幫助下完成的。

在你的情況,你將不得不改變OnTriggerEnterSetCountText一下,讓他們返回IEnumerable類型:

IEnumerable OnTriggerEnter(Collider other) 
{ 
    if (other.gameObject.CompareTag ("Pick Up")) 
    { 
     other.gameObject.SetActive (false); 
     count = count + 1; 
     yield return SetCountText(); 
    } 
} 

IEnumerable SetCountText() 
{ 
    countText.text = "Count: " + count.ToString(); 
    if (count >= 1) 
    { 
     winText.text = "You Win!"; 
     yield return new WaitForSeconds(5); // Wait for seconds before changing level 
     Application.LoadLevel(1); 
    } 
} 
+0

作爲一個初學者,OP應該使用'Invoke'。這是十億次重複 - 沒有人應該回答它。這個網站正在轉向垃圾,因爲人們不斷回答質量最低的Unity問題。 – Fattie

相關問題