我刚刚开始在团结中学习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 =&#34;你赢了!&#34;; 和Application.LoadLevel(1);所以你实际上可以阅读文本。我希望有人可以帮助我!
答案 0 :(得分:5)
使用Coroutine(因为我看到这是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);
}
}
答案 1 :(得分:0)
我可以假设它是一个Windows窗体应用程序,因此您最好不要使用Thread.Sleep,因为它会阻止UI线程。
相反,使用: System.Windows.Forms.Timer
答案 2 :(得分:-1)
在Unity中,等待通常是在WaitForSeconds类的帮助下完成的。
在您的情况下,您需要稍微更改SetCountText
和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);
}
}
类型:
{{1}}