Unity C#-NullReferenceException:对象引用未设置为对象的实例 [英] Unity c# - NullReferenceException: Object reference not set to an instance of an object

查看:672
本文介绍了Unity C#-NullReferenceException:对象引用未设置为对象的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在runtime期间与我的imagetext一起具有error.我在hierarchy中创建的两个对象都正确命名,但是显然我的脚本找不到它们.为什么我写的内容还不够?我在error中得到的全部是Object reference,没有设置为对象的实例,但是当我在层次结构中有一个实例时,我不明白为什么需要创建该对象的实例. 我对unity和c#还是比较陌生,并且无法通过搜索找到任何真正的解释性答案,并且unity教程不是很有帮助,因为我敢肯定这只是关于c#

Im having an error during runtime with my image and text. I have both objects created in my hierarchy named correctly but apparently my script cant find them. 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. 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#

private Text serverInfoText;
private GameObject serverInfoImage;

void Awake()
{
    serverInfoImage = GameObject.Find ("ServerInfoImage");
    serverInfoImage.SetActive (false);
    serverInfoText = GameObject.Find("ServerInfoText").GetComponent<Text>();
}

推荐答案

无需看场景就可以说.

尝试的事情:

  • GameObject.Find仅适用于活动的游戏对象.确保游戏对象在场景视图中未显示为灰色.
  • 再次检查名称字符串是否正确,并使用Debug.Log进行健全性检查.
  • 您没有提到实际发生异常的那一行.在上面的代码中,有可能在两个位置引发异常:如果serverInfoImage为null,则在SetActive()上;如果未找到ServerInfoText对象,则在GetComponent<Text>()上.阅读您收到的实际异常消息,并确保您正在查看正确的行/对象.
  • 由于已经在场景中创建了对象,因此使用GameObject.Find获取对对象的引用没有任何好处.通过检查器直接将对对象的引用设置为更有效.此选项具有使用禁用的GameObjects的额外好处.可以将两个成员变量设为私有,或者使用 SerializeField 属性使该属性在检查员.
  • GameObject.Find only works on active game objects. Make sure the game objects are not greyed out in your scene view.
  • Double check the name strings are correct and use Debug.Log to sanity check.
  • You don't mention which line the actual exception occurs. In your above code, it's possible to throw an exception in two locations: on SetActive() if serverInfoImage is null, or on GetComponent<Text>() if the ServerInfoText object is not found. Read the actual exception message you get and make sure you are looking at the correct line/object.
  • Since your objects are already created in your scene, there's no advantage to using GameObject.Find to get references to the objects. It would be more efficient to directly set the references to the objects via the inspector. This option has the added benefit of working with disabled GameObjects. Either make your two member variables private, or use the SerializeField attribute to make the properties visible in the inspector.

这篇关于Unity C#-NullReferenceException:对象引用未设置为对象的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆