Menu
CoddyTech

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 icon

Challenge

Medium

Make every Switchable report when it is switched on and off.

  1. Add an int count; field and void OnEnable(): add 1 to count, then log name + " on (" + count + ")", such as Bubble on (2).
  2. Add void OnDisable() that logs name + " 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

Practice on your own: Unity playground