The Unity manual doesn’t comprehensively explain when Awake(), OnEnable(), OnDisable(), OnDestroy() is called for Scriptable Objects. I wanted to post my findings to help others with the same confusion.
Which functions are called, in the order they are called, for particular events.
Creating a new scriptable object in the project, during editor time:
Only the created scriptable object
- Awake()
- OnEnable()
Script reload:
All Scriptable objects in the project
- OnDisable()
- OnEnable()
Scriptable object instantiated at runtime:
Only the instantiated scriptable object
- Awake()
- OnEnable()
Scriptable object instance destroyed at runtime:
Only the destroyed scriptable object instance
- OnDisable()
- OnDestroy()
Editor startup:
All Scriptable objects in the project
- Awake()
- OnEnable()
Destroying an object in the project, during editor time:
0. No callbacks are called
Copy/pasteable code.
using UnityEngine;
[CreateAssetMenu(fileName = "MySO", menuName = "MySO", order = 1)]
public class MySO : ScriptableObject
{
private void OnDestroy()
{
Debug.Log("2. OnDestroy(): This scriptable object was destroyed at runtime.");
}
private void OnDisable()
{
if (Application.isPlaying)
{
Debug.Log("1. OnDisable(): This scriptable object was destroyed at runtime.");
}
else
{
Debug.Log("1. OnDisable(): Scripts were reloaded due to code changes or domain reload.");
}
}
private void OnEnable()
{
if (Application.isPlaying)
{
Debug.Log("2. OnEnable(): This scriptable object was instantiated at runtime.");
}
else
{
Debug.Log("2. OnEnable(): The editor was started OR Scripts were reloaded due to code changes or domain reload OR this scriptable object was created at editor time.");
}
}
private void Awake()
{
if (Application.isPlaying)
{
Debug.Log("1. Awake(): This scriptable object was instantiated at runtime.");
}
else
{
Debug.Log("1. Awake(): The editor was started OR this scriptable object was created in the project at editor time.");
}
}
}