C#中对象的实例
Instance of an object in C#
我在尝试制作的游戏中遇到错误。我收到以下错误。
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")
返回了null,
然后 .GetComponent("Canvas");
抛出异常。
来自 GameObject.FindWithTag 文档:
Description
Returns one active GameObject tagged tag
. Returns null
if no
GameObject was found.
所以您可能想尝试捕获错误:
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
}
我在尝试制作的游戏中遇到错误。我收到以下错误。
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")
返回了null,
然后 .GetComponent("Canvas");
抛出异常。
来自 GameObject.FindWithTag 文档:
Description
Returns one active GameObject tagged
tag
. Returnsnull
if no GameObject was found.
所以您可能想尝试捕获错误:
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
}