Version: Unity 6.5 Alpha (6000.5)
LanguageEnglish
  • C#

OnCodeInitializingAttribute

class in Unity.Scripting.LifecycleManagement

/

Inherits from:Unity.Scripting.LifecycleManagement.LifecycleAttributeBase

Suggest a change

Success!

Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable.

Close

Submission failed

For some reason your suggested change could not be submitted. Please <a>try again</a> in a few minutes. And thank you for taking the time to help us improve the quality of Unity Documentation.

Close

Cancel

Description

Marks a static method as a callback to be invoked after managed objects have been restored following a code reload.

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.

Additional resources: OnCodeDeinitializingAttribute, OnCodeLoadedAttribute

using Unity.Scripting.LifecycleManagement;
using UnityEngine;

public static partial class GameManagerRegistry { [OnCodeInitializing] static void RebuildRegistry() { var managers = Object.FindObjectsByType<GameManager>(FindObjectsSortMode.None); 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"; }

Inherited Members