Version: 2018.2 (switch to 2018.1 or 2017.4)
Creating components with scripting
Tags
Other Versions

Deactivating GameObjects

A GameObjectThe fundamental object in Unity scenes, which can represent characters, props, scenery, cameras, waypoints, and more. A GameObject’s functionality is defined by the Components attached to it. More info
See in Glossary
can be temporarily removed from the sceneA Scene contains the environments and menus of your game. Think of each unique Scene file as a unique level. In each Scene, you place your environments, obstacles, and decorations, essentially designing and building your game in pieces. More info
See in Glossary
by marking it as inactive. This can be done using its activeSelf property from a script or with the activation checkbox in the inspector

A GameObject’s activation checkbox

Effect of deactivating a parent GameObject

When a parent object is deactivated, the deactivation also overrides the activeSelf setting on all its child objects, so the whole hierarchy from the parent down is made inactive. Note that this does not change the value of the activeSelf property on the child objects, so they will return to their original state once the parent is reactivated. This means that you can’t determine whether or not a child object is currently active in the scene by reading its activeSelf property. Instead, you should use the activeInHierarchy property, which takes the overriding effect of the parent into account.

This overriding behaviour was introduced in Unity 4.0. In earlier versions, there was a function called SetActiveRecursively which could be used to activate or deactivate the children of a given parent object. However, this function worked differently in that the activation setting of each child object was changed - the whole hierarchy could be switched off and on but the child objects had no way to “remember” the state they were originally in. To avoid breaking legacy code, SetActiveRecursively has been kept in the API for 4.0 but its use is not recommended and it may be removed in the future. In the unusual case where you actually want the children’s activeSelf settings to be changed, you can use code like the following:-

// JavaScript
function DeactivateChildren(g: GameObject, a: boolean) {
    g.activeSelf = a;
    
    for (var child: Transform in g.transform) {
        DeactivateChildren(child.gameObject, a);
    }
}


// C#
void DeactivateChildren(GameObject g, bool a) {
    g.activeSelf = a;
    
    foreach (Transform child in g.transform) {
        DeactivateChildren(child.gameObject, a);
    }
}

Did you find this page useful? Please give it a rating:

Creating components with scripting
Tags