Menu
CoddyTech

Show and Hide

Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 34 of 67.

SetActive(false) switches a whole GameObject off: it is not drawn, it no longer collides, the scripts on it stop getting Update(), and its children go with it. SetActive(true) brings it all back, and activeSelf tells whether it is on. This script on a button hides the door in its door field at a mouse click:

public GameObject door;

void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        door.SetActive(false);
    }
}

A script that hides its own object, with gameObject.SetActive(false), cannot bring it back, because its Update() no longer runs. So the switch lives on another object, with a reference to the one it shows and hides.

enabled switches off one component and leaves the rest of the object alone. GetComponent<Renderer>().enabled = false makes an object invisible, but its collider still blocks things: an invisible wall. A script with enabled = false gets no more Update() calls, but the object stays in the scene, still drawn and still colliding, and its other components keep working.

challenge icon

Challenge

Medium

The Lever's script holds the Bridge in its bridge field. Make Space work the bridge: the first press hides it, the next press brings it back, and so on, one switch per press.

Hide the whole bridge, collider and all, so nobody can stand on a bridge that is not there.

Press Play, press Space a few times, then Check.

Try it yourself

using UnityEngine;

public class BridgeSwitch : MonoBehaviour
{
    public GameObject bridge;

    void Update()
    {
        // Space hides the bridge, and the next press shows it again
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Unity Scripting Basics