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

AutoStaticsCleanupAttribute

class in Unity.Scripting.LifecycleManagement

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

Resets static variables automatically on entering or exiting Play mode with domain reload disabled.

This attribute can be applied to classes, structs, fields, properties, and events. Applying it to a class or struct ensures all static members of the class or struct are automatically reset.

[AutoStaticsCleanup] resets state as follows:

  • Static fields are restored by reapplying their field initializer. If no initializer is present, the field is reset to its C# default value. For example, static int myInt = 5; resets to 5.
  • For reference-type fields initialized with new, the initializer is evaluated again, so a new instance is created. For example, static MyObj obj = null; resets to null and static MyObj obj = new(); creates a fresh MyObj when Play mode starts.
  • static readonly List<T> and static readonly Dictionary<TKey,TValue> are a special case: instead of replacing the instance, the existing collection is preserved and Clear is called. Non-readonly static lists and dictionaries are reset normally by reapplying their initializer.

For more information, refer to Enter Play mode with domain reload disabled in the manual.

using Unity.Scripting.LifecycleManagement;
using UnityEditor.Scripting.LifecycleManagement;
using UnityEngine;
public partial class MyCounterClass : MonoBehaviour
{
    [AutoStaticsCleanup]
    public static int cleanedUpCounter = 0;

void Start() { Debug.Log(cleanedUpCounter); // Counter value is reset each time entering Play Mode cleanedUpCounter++; } }