如何通过Unity 4.6中的C#脚本更改2个不同的UI文本

时间:2015-05-05 13:26:02

标签: c# text unity3d textbox

我正在尝试使用C#在monodevelop中更改Unity 4.6.3中的两个不同的文本字段。

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

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

                       [...truncated...]

        GuessUI.text = "500"; 
        TextUI.text = "Welcome to Number Wizard!";
    }

我收到此错误:

NullReferenceException: Object reference not set to an instance of an object
NumberWizard.Start () (at Assets/Scripts/NumberWizard.cs:16)
 

enter image description here

enter image description here

enter image description here

我做错了什么?

2 个答案:

答案 0 :(得分:1)

您想要实现的目标尚不清楚,但如果您想要依赖某些内容来更新Text,则应使用IF语句。如果要更新2 Text,则NumberWizard脚本应该使用2个Text参数。或者,您可以使用GameObject.FindByName()方法。 例如:

TextUI = GameObject.FindByName("TextUI");
GuessUI = GameObject.FindByName("GuessUI");
TextUI.Text = "Test1";
GuessUI.Text = "Test2";

注意:您的代码和屏幕截图并不匹配。如果你有2个文本组件,那么Unity Editor应该显示它们。

答案 1 :(得分:0)

我没有弄清楚为什么那不起作用但现在已经解决了:

public Text GuessUI;
public Text TextUI;

TextUI.text = "Welcome to Number Wizard!";
GuessUI.text = "500"; 

我在检查员中设置了这个:

enter image description here