OnEnable and OnDisable
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 72 of 85.
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
MediumMake every Switchable report when it is switched on and off.
- Add an
int count;field andvoid OnEnable(): add 1 tocount, then logname + " on (" + count + ")", such asBubble on (2). - Add
void OnDisable()that logsname + " off".
Press Play and press Space: the Console shows Player on (1), then Bubble on (1) and Bubble off. 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"
}
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 Star12The Script Lifecycle
Awake and StartUpdate and LateUpdateOnEnable and OnDisableThe Lifecycle OrderRecap: Lifecycle LoggerPractice on your own: Unity playground