致力于熟悉 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 或使用GetComponent
(Tutorial) 或其变体之一引用它。
因此,如果该Text
组件附加到与您的脚本相同的游戏对象,那么您可以使用GetComponent
(API)在运行时获取引用
private void Awake ()
{
if(!myText) myText = GetComponent<Text>();
myText.text = "@organickoala718" ;
}
还检查使用组件控制游戏对象
顺便说一句,你应该删除空的方法Start
和Update
完全。如果它们存在,它们会被 Unity 引擎作为消息调用,因此不需要存在,只会导致不必要的开销。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句