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

OnCodeDeinitializingAttribute

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 before managed objects are backed up for a code reload.

Methods marked with this attribute are called before Unity serializes managed objects in preparation for a code reload. This is the counterpart to OnCodeInitializingAttribute.

Use this callback to:

  • Prepare objects for serialization.
  • Flush pending state to serialized fields.
  • Clean up non-serializable references.

This is a method attribute that can only be applied to static methods with no parameters and return type void.

Additional resources: OnCodeInitializingAttribute, OnCodeUnloadingAttribute

using Unity.Scripting.LifecycleManagement;
using UnityEngine;

public static partial class StateSynchronizer { [OnCodeDeinitializing] static void FlushPendingState() { var objects = Object.FindObjectsByType<DirtyTracker>(FindObjectsSortMode.None); foreach (var obj in objects) { if (obj.IsDirty) { obj.FlushToSerializedFields(); } } Debug.Log($"Flushed state for {objects.Length} objects"); } }

public class DirtyTracker : MonoBehaviour { [SerializeField] private int persistedValue; private int runtimeValue;

public bool IsDirty => runtimeValue != persistedValue;

public void FlushToSerializedFields() { persistedValue = runtimeValue; } }

Inherited Members