Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/unity3d/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Unity3d 将游戏对象的名称与其父名称进行比较_Unity3d - Fatal编程技术网

Unity3d 将游戏对象的名称与其父名称进行比较

Unity3d 将游戏对象的名称与其父名称进行比较,unity3d,Unity3d,这是我的密码: GameObject no=GameObject.Find("LevelButton"); GameObject noparent=GameObject.Find("LevelPHwithrect (" + (i + 1) + ")"); 问题是我能够找到游戏对象,但是当我调用 if(no.transform.parent.name==noparent.transform.name) { //do something } 我得到一个错误,说null reference

这是我的密码:

GameObject no=GameObject.Find("LevelButton");
GameObject noparent=GameObject.Find("LevelPHwithrect (" + (i + 1) + ")");
问题是我能够找到
游戏对象
,但是当我调用

if(no.transform.parent.name==noparent.transform.name)
{
    //do something
}
我得到一个错误,说null reference,即使它正在查找对象,并且我已经将no的parent设置为noparent


如果这篇文章中有错误,请原谅我,因为这是我处理堆栈溢出的第一天。

如果您有一个脚本附加到“否”游戏对象,请尝试使用:

this.gameObject.name == this.gameObject.transform.parent.gameObject.name

GameObject.Find
有点危险,因为你很容易在Unity界面中拼错或更改游戏对象的名称,而忘记在代码中更改它。我可以问你为什么需要这个片段吗?

使用
游戏对象的
名称
属性,而不是
转换
。还要进行防御性编码并检查
null

if (no != null && noparent != null && no.name == noparent.name)
{
    //do something
}

谢谢,伙计,我想用不同的方式做一些动作。谢谢你的帮助。你可以选择一个正确的答案(使用左边的复选标记)。如果没有帮助,请添加您自己的答案并进行检查。你也可以投票选出你认为合适的答案。