[英]Unity c# - NullReferenceException: Object reference not set to an instance of an object
Im having an error
during runtime
with my image
and text
.我的
image
和text
在runtime
error
。 I have both objects created in my hierarchy
named correctly but apparently my script cant find them.我在我的
hierarchy
创建的两个对象命名正确,但显然我的脚本找不到它们。 Why isn't what i have written not sufficient?为什么我写的还不够? All i get in the
error
is Object reference
not set to an instance of an object, but i don't understand why i need to create an instance of this object when i have one in my hierarchy.我在
error
得到的只是Object reference
未设置为Object reference
的实例,但我不明白为什么当我的层次结构中有一个对象时我需要创建该对象的实例。 I'm still relatively new to both unity and c#
and couldn't find any real explanatory answer by searching and the unity tutorials weren't very helpful since I'm sure its just a basic question about c#
我对 unity 和
c#
仍然相对较新,通过搜索找不到任何真正的解释性答案,并且 unity 教程不是很有帮助,因为我确定它只是一个关于c#
的基本问题
private Text serverInfoText;
private GameObject serverInfoImage;
void Awake()
{
serverInfoImage = GameObject.Find ("ServerInfoImage");
serverInfoImage.SetActive (false);
serverInfoText = GameObject.Find("ServerInfoText").GetComponent<Text>();
}
Impossible to say without looking at your scene.不看你的场景就无法说。
Things to try:尝试的事情:
GameObject.Find
only works on active game objects. GameObject.Find
仅适用于活动的游戏对象。 Make sure the game objects are not greyed out in your scene view.Debug.Log
to sanity check.Debug.Log
进行完整性检查。SetActive()
if serverInfoImage
is null, or on GetComponent<Text>()
if the ServerInfoText object is not found.serverInfoImage
为 null,则在SetActive()
如果未找到 ServerInfoText 对象,则在GetComponent<Text>()
。 Read the actual exception message you get and make sure you are looking at the correct line/object.GameObject.Find
to get references to the objects.GameObject.Find
获取对对象的引用没有任何优势。 It would be more efficient to directly set the references to the objects via the inspector.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.