通过名称访问GameObject并在unity3d中执行setActive(false)操作

时间:2019-07-16 03:25:42

标签: visual-studio unity3d

我正尝试访问cylinder下的特定对象hallway,如下图所示。我正在使用以下脚本来获取对该对象的引用,但得到了null pointer exception

GameObject cylinder = GameObject.Find("/hallway/Cylinder");

enter image description here

1 个答案:

答案 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");