deathracer
deathracer

Reputation: 305

access GameObject by name and perform setActive(false) operation in unity3d

I am trying to get access to a specific object cylinder under the hallway as shown in the hierarchy view image below. I am using the following script to get a reference to the object but I get a null pointer exception:

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

enter image description here

Upvotes: 0

Views: 61

Answers (1)

siusiulala
siusiulala

Reputation: 1060

You can use Resources.FindObjectsOfTypeAll to find the inactive 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;
}

Usage:

GameObject cylinder = FindGameObject("Cylinder");

or

GameObject cylinder = FindGameObject("Cylinder","hallway");

Upvotes: 1

Related Questions