如何:在脚本中正确引用文本 UI 组件

How to: Correctly reference a Text UI component in a script

正在努力熟悉 C# 和统一开发。今天我正在努力在我的脚本中获取对 Text UI 对象的引用。以下代码会产生此错误:

NullReferenceException: Object reference not set to an instance of an object
handle.Awake () (at Assets/handle.cs:20)

脚本如下所示:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using playPORTAL.Profile;
using UnityEngine.UI;

public class handle : MonoBehaviour
{

    public Text myText;

    // Start is called before the first frame update
    void Start()
    {

    }

    void Awake()
    {
        myText.text = "@organickoala718" ;
    }

    // Update is called once per frame
    void Update()
    {

    }
}

需要改进哪些地方才能正确获取对文本 UI 元素的引用?

您需要从另一个脚本设置 handle 实例的 myText 值,或者在您选择游戏对象后在 Unity 编辑器的检查器 window 中设置它添加了您的 handle 组件。

总的来说:与任何其他组件相同。

要么通过 Inspector 引用它,要么使用 GetComponent(教程)或其变体之一。


因此,如果 Text 组件与您的脚本附加到同一个游戏对象,那么您可以使用 GetComponent(API) 在运行时获取引用

private void Awake ()
{
    if(!myText) myText = GetComponent<Text>();
    myText.text = "@organickoala718" ;
}

也结帐Controlling GameObjects with Components


顺便说一句,您应该完全删除空方法 StartUpdate。如果它们存在,它们将被 Unity 引擎称为消息,因此不需要存在,只会造成不必要的开销。

您需要将引用的对象从场景中的 Unity 编辑器拖到脚本本身。 首先将您制作的脚本附加到 Unity 场景中的游戏对象。 然后将 "text" 组件拖到您最近附加到 GameObject

的脚本中

这将解决您遇到的问题。


另一种方法是声明一个

public GameObject UITextElement;

而不是像您那样使用 public 文本。 和我之前写的一样,在脚本中写:

UITextElement.GetComponent().text = "Write your text here!";