C# C中对象的实例#
我在尝试制作的游戏中遇到了一个bug。我得到以下错误C# C中对象的实例#,c#,unity3d,C#,Unity3d,我在尝试制作的游戏中遇到了一个bug。我得到以下错误 NullReferenceException: Object reference not set to an instance of an object 这段代码在我的另一个脚本中运行良好,但在这段脚本中,它继续通过此错误。我想我把它设置为对象的一个实例,但我想不是 UnityEngine.Component book001GUIOld = GameObject.FindWithTag("Book001Canvas").GetCompone
NullReferenceException: Object reference not set to an instance of an object
这段代码在我的另一个脚本中运行良好,但在这段脚本中,它继续通过此错误。我想我把它设置为对象的一个实例,但我想不是
UnityEngine.Component book001GUIOld = GameObject.FindWithTag("Book001Canvas").GetComponent("Canvas");
UnityEngine.Behaviour book001GUI = (UnityEngine.Behaviour)book001GUIOld;
有什么建议吗?如果您需要更多的代码,请告诉我。我也试过了
UnityEngine.Behaviour book001GUI = GameObject.FindWithTag("Book001Canvas").GetComponent("Canvas") as behaviour;
必须是因为
GameObject.FindWithTag(“Book001Canvas”)
返回空值,
然后.GetComponent(“画布”)代码>引发异常。来自文档:
说明
返回一个标记为标记的活动游戏对象。如果否,则返回null
找到游戏对象
因此,您可能希望尝试捕捉错误:
var book001Canvas = GameObject.FindWithTag("Book001Canvas");
if (book001Canvass != null)
{
UnityEngine.Component book001GUIOld = book001Canvas.GetComponent("Canvas");
}
else
{
// Recover from not finding an object with the Book001Canvas tag
}
只需找出对象为null但不应为null的最底层堆栈…NullReference是最容易调试的错误之一..GameObject似乎是一个静态类,.FindWithTag是一个静态方法。不?啊,我想你是对的。