我正尝试访问cylinder
下的特定对象hallway
,如下图所示。我正在使用以下脚本来获取对该对象的引用,但得到了null pointer exception
:
GameObject cylinder = GameObject.Find("/hallway/Cylinder");
答案 0 :(得分:1)
您可以使用Resources.FindObjectsOfTypeAll查找无效的GameObject。
GameObject FindGameObject(string name, string parentName = "")
{
foreach (GameObject go in Resources.FindObjectsOfTypeAll(typeof(GameObject)) as GameObject[])
{
if (go.name == name)
{
if (parentName == "" || go.transform.parent.name == parentName)
return go;
}
}
return null;
}
用法:
GameObject cylinder = FindGameObject("Cylinder");
或
GameObject cylinder = FindGameObject("Cylinder","hallway");