根据按钮单击更改文本

时间:2015-02-21 04:33:48

标签: button text unity3d unity3d-gui

我正在使用Unity3d

我试图追踪问题的来源并且没有成功。文字更新"猜猜"按键完成后正常发生,但没有点击按钮(两者都登录异常)。

The code:

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

public class NumberWizard : MonoBehaviour
{
    public Text guessText;
    int min;
    int max;
    int guess;

    public void Higher ()
    {
        min = guess;
        NextGuess ();
    }

    public void Lower ()
    {
        max = guess;
        NextGuess ();
    }

    public void Correct ()
    {
        print ("I won!");
        StartGame ();
    }

    private void StartGame ()
    {
        min = 1;
        max = 1000;
        guess = 500;
        guessText.text = guess.ToString();
        print (guess);
    }

    private void NextGuess ()
    {
        guess = (max + min) / 2;
        guessText.text = guess.ToString();
        print (guess);
    }


    // Use this for initialization
    void Start ()
    {
        StartGame ();
    }

    // Update is called once per frame
    void Update ()
    {
        if (Input.GetKeyDown (KeyCode.UpArrow)) {
            Higher ();
        } else if (Input.GetKeyDown (KeyCode.DownArrow)) {
            Lower ();
        } else if (Input.GetKeyDown (KeyCode.Return)) {
            Correct ();
        }

    }
}

顺便说一下,我把按钮放在另一个名为" LevelManager"的控制器上。我已将[RequireComponent(typeof(LevelManager))]添加到课程声明之上,但它没有效果。

基本上,它表示在guessText.text = guess.ToString(); object没有设置为实例,但是我在Unity3d中设置了引用特定文本并且它应该使用NumberWizard.cs

2 个答案:

答案 0 :(得分:1)

创建此脚本时,需要将其附加到GameObject。当您完成编码时,它应该附加到Empty gameObject。然后,当您从编辑器中选择脚本时,您的公共变量Text guessText将在edior上可用,现在您必须将您创建的GUIText拖放到guessText属性。< / p>

答案 1 :(得分:0)

错误说你必须初始化变量,无论是通过做一个&#34; new&#34;或者像Dinal所说的那样将它作为一个游戏拖拽对象。