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
MediumThe 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
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Unity Scripting Basics
1Your First Script
Hello, UnityPlace the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube4Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot7Project: Catch the Star
The CatcherA Falling Star5Transforms and Hierarchy
Parents and ChildrenScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon6GameObjects and Components
References in the InspectorGet a ComponentMissing ComponentsAdd a ComponentRequireComponentShow and HideRecap: Light Switch