在新的Unity 4.6文本对象中引用TextField

时间:2014-09-22 01:18:59

标签: text unity3d

我有一个简单的倒计时脚本组件附加了一个包含单个Text组件的Canvas对象。 '指令'应该引用TextField,不是吗?当我通过调用startCountdown来运行它时,脚本会在行

的while循环中挂起
Debug.Log ("TIMER countdown  time = "+time+ " and instruction = "+instruction);

指令变量根本没有跟踪。 public var'time'在检查器中设置为大于0的某个值。

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

public class Timer : MonoBehaviour {

    public int time;

    Text instruction;

    public void Start () {
        instruction = GetComponent<Text>();
    }

    public void startCountdown() {
        StartCoroutine (countdown ());
        Debug.Log ("YES TIMER START!");
    }

    IEnumerator countdown() {
        while (time > 0) {
            Debug.Log ("TIMER countdown  time = " + time + " and instruction = " + instruction);
            yield return new WaitForSeconds(1);

            instruction.text = time.ToString();

            time -= 1;
        }

        instruction.text = "Blast Off!";
    }
}

1 个答案:

答案 0 :(得分:0)

我认为你的GetComponent可能什么都没有返回。很难说,因为我不知道你附加脚本的游戏对象是什么。我使用public来引用Text UI元素。

我在Unity 4.6中使用它。您必须将对Text组件的引用拖到脚本中。我将我的脚本附加到一个名为SceneController的空gameObject。以下适用于我(倒计时,然后爆炸!)。

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

public class Timer : MonoBehaviour {

    public int time;

    public Text instruction;

    public void Start () {
        startCountdown();
    }

    public void startCountdown() {
        StartCoroutine (countdown ());
        Debug.Log ("YES TIMER START!");
    }

    IEnumerator countdown() {
        while (time > 0) {
            Debug.Log ("TIMER countdown  time = " + time + " and instruction = " + instruction.text);
            yield return new WaitForSeconds(1);

            instruction.text = time.ToString();

            time -= 1;
        }

        instruction.text = "Blast Off!";
    }
}