Documentation

Unity Engine


User Manual

Script Reference

Unity Engine


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

[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
    Awake
    /
    OnEnable
    calls.
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
static
methods with no parameters and return type
void
.

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.

Inheritance

Inherited Members