简体   繁体   English

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

[英]How change 2 different UI text via C# script in Unity 4.6

I'm trying to change two different text fields in Unity 4.6.3 with C# in monodevelop. 我正在尝试在monodevelop中使用C#更改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!";
    }

I'm getting this error: 我收到此错误:

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

在此处输入图片说明

在此处输入图片说明

在此处输入图片说明

What i am doing wrong? 我做错了什么?

It is not so clear what you want to achieve but if you want to update Text with depend on something then you should use IF statement. 尚不清楚要实现什么,但是如果要依赖于某些内容来更新Text,则应使用IF语句。 If you want to update 2 Text then NumberWizard script should take 2 Text parameters. 如果要更新2个文本,则Nu​​mberWizard脚本应采用2个文本参数。 Alternatively, you can use GameObject.FindByName() method. 或者,您可以使用GameObject.FindByName()方法。 Example: 例:

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

Note: Your code and screenshots doesn't match. 注意:您的代码和屏幕截图不匹配。 If you've 2 Text components then Unity Editor should show them. 如果您有2个Text组件,则Unity Editor应该显示它们。

I didn't figured out why that wasn't working but now is solved: 我没有弄清楚为什么它不起作用,但现在已解决:

public Text GuessUI;
public Text TextUI;

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

And I set up this in inspector: 我在检查器中设置了这个:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM