Show and Hide
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 48 of 85.
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
MediumMake Space hide the bridge and bring it back.
- In
Update(), onInput.GetKeyDown(KeyCode.Space), callbridge.SetActive(...)to switch the whole bridge, collider and all. - Pass the opposite of its state:
bridge.SetActive(!bridge.activeSelf);.
Press Play and press Space a few times: the bridge vanishes and comes back. 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
}
}
All lessons in Unity Scripting Basics
1C# Basics in Unity
Hello, UnityVariablesDecimals Need an fText in the ConsoleVariables That RememberIf and ElseCompare NumbersRecap: Coin Collector2Make It Move
Place the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube5Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot8GameObjects and Components
References in the InspectorGet a ComponentMissing ComponentsAdd a ComponentRequireComponentShow and HideRecap: Light Switch6Transforms and Hierarchy
Parents and ChildrenHoist the FlagScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon9Project: Catch the Star
The CatcherA Falling StarPractice on your own: Unity playground