OnCodeInitializingAttribute
Marks a static method as a callback to be invoked after managed objects have been restored following a code reload.
Read time 4 minutesLast updated 4 days ago
Definition
- Type: Class
- Namespace: Unity.Scripting.LifecycleManagement
- Assembly: Unity.Scripting
- Inherits from: LifecycleAttributeBase
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]public sealed class OnCodeInitializingAttribute : LifecycleAttributeBase
Remarks
Methods marked with this attribute are called after Unity has restored (deserialized) managed objects following a code reload. At this point:
- All assemblies are loaded.
- Serialized MonoBehaviour and ScriptableObject data has been restored.
- Objects exist but have not yet received /
Awakecalls.OnEnable
Use this callback to:
- Rebuild runtime caches that depend on restored object state.
- Perform initialization requiring access to deserialized data.
- Set up cross-references between restored objects.
This is a method attribute that can only be applied to methods with no parameters and return type .
staticvoidAdditional Resources: OnCodeDeinitializingAttribute, OnCodeLoadedAttribute
Examples
using Unity.Scripting.LifecycleManagement;using UnityEngine;public static partial class GameManagerRegistry{ [OnCodeInitializing] static void RebuildRegistry() { var managers = Object.FindObjectsByType<GameManager>(); Debug.Log($"Found {managers.Length} GameManager instances after restore"); foreach (var manager in managers) { Debug.Log($"Manager '{manager.name}' state: {manager.savedState}"); } }}public class GameManager : MonoBehaviour{ public string savedState = "Initial";}
Constructors
Constructor | Description |
|---|---|
| OnCodeInitializingAttribute() | Marks the decorated static method to be invoked after Unity has deserialized and restored all managed objects following a domain reload. |