OnEnable and OnDisable
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 57 of 67.
OnEnable() runs every time a script becomes active: when its object first appears (right after Awake()), and again each time the object is shown with SetActive(true) or the script is switched back on with enabled = true. OnDisable() runs each time the object is hidden, the script is switched off, or the object is destroyed.
A portal that another script opens and closes with SetActive can report on itself:
void OnEnable()
{
Debug.Log("Portal open");
}
void OnDisable()
{
Debug.Log("Portal closed");
}The portal logs Portal open when the scene starts. Hiding it and showing it again logs Portal closed, then Portal open, while Awake() and Start() do not run a second time. So code that must happen on every appearance, such as resetting a timer or counting visits, goes in OnEnable(). While the portal is hidden its Update() does not run, which is why the opening and closing is done by a script on another object.
Challenge
MediumThe Switchable script is on the Player and on its shield, the Bubble, which starts hidden. On the Player, target is the Bubble, and Space switches the Bubble on and off; that part is written.
Make every Switchable report on itself:
- each time it is switched on, add 1 to a count and log its name,
onand the count in brackets, for exampleBubble on (2); - each time it is switched off, log its name and
off:Bubble off.
When the game starts, the Player logs Player on (1): it is switched on too. Press Play, press Space a few times, then Check.
Try it yourself
using UnityEngine;
public class Switchable : MonoBehaviour
{
public GameObject target;
void Update()
{
if (target != null && Input.GetKeyDown(KeyCode.Space))
{
target.SetActive(!target.activeSelf);
}
}
// Each time this object is switched on: count it and log "<name> on (<count>)"
// Each time it is switched off: log "<name> off"
}
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 Star10The Script Lifecycle
Awake and StartUpdate and LateUpdateOnEnable and OnDisableThe Lifecycle OrderRecap: Lifecycle Logger5Transforms and Hierarchy
Parents and ChildrenScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon