Documentation

Unity Engine


User Manual

Script Reference

Unity Engine


OnCodeDeinitializingAttribute

Marks a static method as a callback to be invoked before managed objects are backed up for a code reload.
Read time 4 minutesLast updated 4 days ago

Definition

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]public sealed class OnCodeDeinitializingAttribute : LifecycleAttributeBase

Remarks

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
.

Examples

using Unity.Scripting.LifecycleManagement;using UnityEngine;public static partial class StateSynchronizer{ [OnCodeDeinitializing] static void FlushPendingState() { var objects = Object.FindObjectsByType<DirtyTracker>(); 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; }}

Constructors

Constructor

Description

OnCodeDeinitializingAttribute()Marks the decorated static method to be invoked before Unity serializes managed objects in preparation for a code reload. Methods are called in reverse registration order.

Inheritance

Inherited Members