【问题标题】:How to: Correctly reference a Text UI component in a script如何:在脚本中正确引用文本 UI 组件
【发布时间】:2019-11-05 15:18:19
【问题描述】:

致力于熟悉 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()
    {

    }
}

为了正确获取对 Text UI 元素的引用,需要改进哪些方面?

【问题讨论】:

  • 这个错误通常是由于忘记在inspector中分配GameObject引起的。您是否已将文本 UI 游戏对象拖放到检查器中的“我的文本”字段中以获取句柄组件?

标签: c# unity3d game-engine


【解决方案1】:

通常:与任何其他组件的方式相同。

通过 Inspector 引用它或使用 GetComponent(Tutorial) 或其变体之一。


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

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

也结帐Controlling GameObjects with Components


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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

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

      这会解决你的问题。


      另一种方法是声明一个

      公共游戏对象 UITextElement;

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

      UITextElement.GetComponent().text = "在这里写你的文字!";

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-08-31
        • 2013-02-02
        • 1970-01-01
        • 2017-01-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多