# 2. Unity 6.6 Programming Changes Part of [[Unity 6.6 and 7.0 Updates]]. Previous: [[1. Release Status and the Path to CoreCLR]]. Next: [[3. Unity 7.0 Alpha - CoreCLR, .NET 10 and CSharp 14]]. > [!warning] Code not compiled in Unity > No listing was compiled or run **in the Unity Editor**. > What *was* checked (2026-11-29): all six listings were type-checked with the Roslyn compiler that ships with Unity **6000.6.5f1**, using `-langversion:9` against that Editor's `UnityEngine`/`UnityEditor` module assemblies and .NET Standard 2.1, with **no errors**. `S4` was also compiled without the 6.6 defines to check the pre-6.6 branch. Not checked: the `[AutoStaticsCleanup]` source generator, the serialization rules analyzer, the Inspector, and anything at runtime. **Language version is unchanged:** 6.6 is **C# 9.0** on Roslyn. The 6.6 C# compiler page lists the same unsupported C# 9 features: *suppress emitting localsinit*, *covariant return types*, *module initializers*, *extensible calling conventions for unmanaged function pointers*, and *init only setters*. Records still need your own `System.Runtime.CompilerServices.IsExternalInit`, and Unity's serializer doesn't support records. What 6.6 changes is how your C# is **loaded, reset, compiled for builds and serialized**. All of it is groundwork for CoreCLR in 7.0. ## 2.1 Domain reload on entering Play mode is off by default (new projects) Official text (New in 6.6): the default for **new projects** is now **Reload Scene only** (Edit > Project Settings > Editor > Enter Play Mode Settings) instead of Reload Domain and Scene. You can turn domain reload back on, but "the recommended best practice is to keep domain reload off to prepare for the forthcoming removal of Mono and the domain reload mechanism in future Unity versions." - **Existing projects keep their setting** when you upgrade. The default changes only for new projects. - **What breaks:** static fields, static events and `static Instance` singletons keep their values from the last Play session. So do anything in a static constructor, which runs once per domain, not once per Play session. - **Where it shows up in this vault:** the Stealth, Crafting and Deckbuilder pitfall tables already mention "statics survive". [[ScriptableObject Architecture]] and [[Architecture and Code Patterns]] already reset static state with `playModeStateChanged` / `SubsystemRegistration`. Those still work in 6.6. The new attributes below are the forward-compatible way. ### Step 1: find the statics Project Auditor in 6.6 includes the **auto statics cleanup Roslyn analyzer**. Enable **Preferences > Use Roslyn Analyzers** for Project Auditor (that is the guide's wording), then run an analysis. Warnings with the **`UAL`** prefix appear on the **Domain Reload** issues page of the Code section. The Path to CoreCLR guide adds that **Project Auditor 2.0.0** can be installed back to Unity 6.0 to find the same issues. ### Step 2: let Unity reset them with `[AutoStaticsCleanup]` `Unity.Scripting.LifecycleManagement.AutoStaticsCleanupAttribute` (assembly `Unity.Scripting`) can go on classes, structs, fields, properties and events. A class or struct that carries it, or contains members that carry it, **must be `partial`** because a source generator injects the reset code. Reset rules, from the Scripting API page: - Static fields get their **field initializer re-applied**, or the C# default if there is no initializer. - For reference-type fields initialized with `new`, the initializer runs again, so you get a fresh instance. - **`readonly` static collections** (anything with a parameterless `Clear`) keep the same instance and have **`Clear()`** called. The initializer must be omitted, `new()`, or the exact declared type. - Fields whose type has an accessible parameterless `Dispose` are **disposed before reset**, except `readonly` ones. - `[NoAutoStaticsCleanup]` is the counterpart. The analyzer warning is resolved by applying either one, so use it to mark a static that should deliberately survive Play sessions. ```csharp // S1_AutoStatics.cs using System.Collections.Generic; using Unity.Scripting.LifecycleManagement; using UnityEngine; // partial is required: a source generator injects the reset code. public partial class ScoreService : MonoBehaviour { [AutoStaticsCleanup] public static int runCount; // reset to 0 [AutoStaticsCleanup] static readonly List<string> runLog = new List<string>(); // readonly collection: Clear() is called void Start() { runCount++; runLog.Add("run " + runCount); Debug.Log(quot;ScoreService run {runCount}, log size {runLog.Count}"); } } ``` **Try it:** with Enter Play Mode set to *Reload Scene only*, enter and exit Play mode three times. Without the attributes the Console counts 1, 2, 3. With them it should print 1 each time. That is the documented behaviour, but I haven't run it. ### Step 3: or write an explicit reset with the lifecycle attributes The 6.6 manual page *Code reload and the code lifecycle* documents symmetrical attributes that "are guaranteed to work with any future scripting runtimes and code reload mechanisms": | Phase | New API | Older equivalent | |---|---|---| | Serializing managed objects during code reload | `[OnCodeDeinitializing]` (`Unity.Scripting.LifecycleManagement`) | none | | Before code is unloaded for a reload | `[OnCodeUnloading]` | `AssemblyReloadEvents.beforeAssemblyReload` | | After assemblies load (Editor and Player) | `[OnCodeLoaded]` | none | | After objects are deserialized, before `Awake`/`OnEnable` | `[OnCodeInitializing]` | `[InitializeOnLoad]`, `[InitializeOnLoadMethod]`, `[RuntimeInitializeOnLoadMethod(SubsystemRegistration)]` | | Entering Play mode (Editor), or Player startup | `[OnEnteringPlayMode]` (`UnityEngine`) | `PlayModeStateChange.EnteredPlayMode` | | Exiting Play mode, or Player quit | `[OnExitingPlayMode]` (`UnityEngine`) | `PlayModeStateChange.ExitingPlayMode` | | Entering / exiting Edit mode | `[OnEnteringEditMode]` / `[OnExitingEditMode]` (`UnityEditor`) | `PlayModeStateChange.EnteredEditMode` / `ExitingEditMode` | ```csharp // S2_ResetHook.cs using System; using UnityEngine; // Static event bus that survives Play mode when domain reload is off. public static class GameEvents { public static event Action<string> Raised; public static void Raise(string id) => Raised?.Invoke(id); // UnityEngine.OnEnteringPlayMode: runs on entering Play mode in the Editor // and when a built Player starts, so no #if UNITY_EDITOR is needed. [OnEnteringPlayMode] static void ResetOnEnteringPlayMode() { Raised = null; } } ``` > [!note] Naming differs between Unity pages > The March 2026 Path to CoreCLR guide uses `[BeforeCodeUnloading]` and `[AfterCodeReloadSerialization]`. The 6.6 *Incompatible .NET API* page maps `AppDomain.CurrentDomain.DomainUnload` to `[OnAssemblyUnloading]`. The 6.6 lifecycle manual page uses `[OnCodeUnloading]` and the other names in the table above. My type-check against 6000.6.5f1 confirmed `OnEnteringPlayMode` and `AutoStaticsCleanup` only, not the other names. Check the Scripting API for your exact editor before you teach a name. ## 2.2 UAC analyzer: .NET APIs that won't survive CoreCLR 6.6 adds a **Unity API Compatibility (UAC)** Roslyn analyzer. It raises compiler **warnings** for reflection and AppDomain APIs that are, or soon will be, incompatible with Unity's assembly lifecycle: | Code | Incompatible API | Use instead | |---|---|---| | `UAC005` | `AppDomain.GetAssemblies` (it can return assemblies that are unloading) | `UnityEngine.Assemblies.CurrentAssemblies.GetLoadedAssemblies()` | | `UAC006` | `AppDomain` events and some methods (for example `DomainUnload`) | Lifecycle attributes (2.1) | | `UAC007` | `Assembly.Location` (empty for stream-loaded assemblies) | `assembly.GetLoadedAssemblyPath()` (`UnityEngine`) | | `UAC020` | `Assembly.LoadFile` / `Assembly.LoadFrom` | `CurrentAssemblies.LoadFromPath(path)` | | `UAC023` | `BinaryFormatter` | Unity serialization, `JsonUtility`, `DataContract` | ```csharp // S6_TypeScan.cs using System; using System.Linq; using UnityEngine.Assemblies; public static class TypeScan { // Replaces AppDomain.CurrentDomain.GetAssemblies() (UAC005). public static Type[] FindImplementations<T>() => CurrentAssemblies.GetLoadedAssemblies() .SelectMany(a => a.GetTypes()) .Where(t => typeof(T).IsAssignableFrom(t) && !t.IsAbstract && !t.IsInterface) .ToArray(); } ``` This is the pattern a command registry like [[In-Game Debug Console and Cheat Tools]] or a plugin scan in [[Custom Inspectors and Editor Tooling]] would use. ## 2.3 Managed Code Variant replaces `DEVELOPMENT_BUILD` and `UNITY_64` This is the 6.6 change most likely to quietly alter your builds. - New per-platform setting: **Edit > Project Settings > Player > Other Settings > Managed Code Variant** (the "Optimization" section, per New in 6.6). It controls how C# is compiled for a Player: optimization, safety checks, profiler instrumentation, and **which diagnostic defines are emitted**. It works independently of the native Development Build checkbox. - The variant names in the docs are **Release** (the default; it defines none of the diagnostic symbols), **Instrumented**, **Checked** and **Debug**. - **`UNITY_ENABLE_CHECKS`** (Debug, Checked) replaces the "safety checks and assertions" meaning of `DEVELOPMENT_BUILD`. - **`UNITY_INCLUDE_INSTRUMENTATION`** (Debug, Checked, Instrumented) replaces the "profiling and diagnostic logging" meaning. - `DEBUG` (Debug variant), `UNITY_ASSERTIONS` and `ENABLE_PROFILER` continue "during this transitional period". In the Editor, both new symbols are always defined. - **`UNITY_64` and `DEVELOPMENT_BUILD` are deprecated.** Using them in `#if` or `[Conditional]` raises **`UAC0008`** / **`UAC0009`**. They still work in 6.6, but warnings-as-errors assemblies fail immediately. **Unity 7.0 alpha already removes both** ("no longer gets defined when building for any platform"). - `BuildOptions.ForceEnableAssertions` is `[Obsolete]`. Use `PlayerSettings.SetManagedCodeVariant(namedBuildTarget, ManagedCodeVariant.Checked)`. > [!important] Behaviour change even if you never wrote `DEVELOPMENT_BUILD` > Built-in features now follow the variant, not the Development Build checkbox. SRP debug overlays, the Rendering Debugger, the Render Graph Viewer, Frame Debugger support and render-graph validation are gated by `UNITY_ENABLE_CHECKS`. Render Graph profiling samplers are gated by `UNITY_INCLUDE_INSTRUMENTATION`. The same goes for Unity Physics integrity checks, Entities Journaling and Adaptive Performance logging. **Because the default variant is Release, a Development Build with default settings no longer contains these diagnostics.** To get the old development-build behaviour, set the variant to **Checked**. Use **Debug** if you also want `DEBUG` and unoptimized code for stepping through in a debugger. Migration rules from the 6.6 upgrade guide: 1. `#if UNITY_64` becomes a **runtime** check on `IntPtr.Size` (8 or 4), because bitness isn't known when scripts compile. 2. Safety checks: `#if UNITY_EDITOR || DEVELOPMENT_BUILD` becomes `#if UNITY_ENABLE_CHECKS`. The Editor defines it, so the `UNITY_EDITOR ||` part is redundant. 3. Logging and profiling: use `UNITY_INCLUDE_INSTRUMENTATION`, or `[Conditional("UNITY_INCLUDE_INSTRUMENTATION")]`. 4. **Anything sensitive that must never ship in a non-development Player:** use the runtime `Debug.isDebugBuild`. A non-development Player can ship with the Checked variant, so `#if UNITY_ENABLE_CHECKS` could compile, for example, token-leaking logs into production. 5. Packages and Asset Store code that also supports older versions can gate on `UNITY_6000_6_OR_NEWER`. ```csharp // S4_Defines.cs using System; using System.Diagnostics; using Debug = UnityEngine.Debug; public static class DevDiagnostics { // Profiling / logging calls: stripped unless the variant includes instrumentation. #if UNITY_6000_6_OR_NEWER [Conditional("UNITY_INCLUDE_INSTRUMENTATION")] #else [Conditional("DEVELOPMENT_BUILD")] #endif public static void Trace(string message) => Debug.Log(message); // Safety checks: compiled in for Debug and Checked variants (and always in the Editor). public static void CheckIndex(int index, int count) { #if UNITY_6000_6_OR_NEWER #if UNITY_ENABLE_CHECKS if (index < 0 || index >= count) throw new IndexOutOfRangeException(quot;{index} is outside 0..{count - 1}"); #endif #else if (Debug.isDebugBuild && (index < 0 || index >= count)) throw new IndexOutOfRangeException(quot;{index} is outside 0..{count - 1}"); #endif } // Anything that must never ship in a non-development Player (for example logging // that could leak tokens): use the runtime check, not the variant symbols. public static void LogSensitive(string payload) { if (Debug.isDebugBuild) Debug.Log("Payload: " + payload); } } ``` An editor menu to flip the variant for Android (Quest) builds. Put it in an `Editor` folder or an editor-only asmdef: ```csharp // Editor/S5_ManagedVariantMenu.cs using UnityEditor; using UnityEditor.Build; public static class ManagedVariantMenu { [MenuItem("Tools/Build/Android Managed Code Variant/Checked")] static void SetChecked() => PlayerSettings.SetManagedCodeVariant(NamedBuildTarget.Android, ManagedCodeVariant.Checked); [MenuItem("Tools/Build/Android Managed Code Variant/Release")] static void SetRelease() => PlayerSettings.SetManagedCodeVariant(NamedBuildTarget.Android, ManagedCodeVariant.Release); [MenuItem("Tools/Build/Android Managed Code Variant/Log Current")] static void LogCurrent() => UnityEngine.Debug.Log(PlayerSettings.GetManagedCodeVariant(NamedBuildTarget.Android)); } ``` Custom SRP build processors: `CoreBuildData.developmentBuild` is `[Obsolete]` and always returns `false` in 6.6 (an error in 7.0 alpha). Use `CoreBuildData.useDiagnosticChecks`. ## 2.4 `Dictionary<TKey, TValue>` serialization 6.6 serializes a field whose declared type is **exactly** `Dictionary<TKey, TValue>` when it has **`[SerializeField]`**. This is opt-in even for public fields. It works on `MonoBehaviour`, `ScriptableObject` and nested `[Serializable]` types, and Unity persists it across domain reloads, scene saves and Play mode. - **Keys and values** can be primitives (`int`, `float`, `double`, `bool`, `string`), enums of 32 bits or smaller, Unity built-ins (`Vector2`, `Vector3`, `Color`), `[Serializable]` classes and structs, and `UnityEngine.Object` references. - **Collections** are allowed as values (`Dictionary<int, List<int>>`) but not as keys. `string` is the only `IEnumerable` key allowed. - **Not allowed:** interfaces and abstract types (except the `UnityEngine.Object` hierarchy) and non-`[Serializable]` types (analyzer `UAC1012`, `UAC1016`). `[SerializeReference]` on a dictionary is invalid (`UAC1014`). A public dictionary without `[SerializeField]` raises `UAC1015`. - Data is stored in **insertion order**. The Inspector draws a sortable two-column list with duplicate-key detection. Prefab instances support per-entry overrides, recorded by **serialized index**, so editing the prefab asset can shift which entry an override applies to. - Limitations: no multi-object editing, and no search or filter in the Inspector. - **Existing wrappers keep working.** A type that derives from `Dictionary` or wraps it, like the `ISerializationCallbackReceiver` list pair in [[Inventory Systems]], stays a normal serialized class. To migrate, add the new field beside the old one, copy the data across with an editor script, check it, and only then delete the old field. If you delete first, you lose the data. ```csharp // S3_Dictionary.cs using System.Collections.Generic; using UnityEngine; public enum ItemId { Coin, Key, Potion } [CreateAssetMenu(menuName = "Tutorials/Loot Table")] public class LootTable : ScriptableObject { // Unity 6.6+: serialized directly, edited as a two-column list in the Inspector. [SerializeField] Dictionary<ItemId, int> weights = new Dictionary<ItemId, int>(); public int WeightOf(ItemId id) => weights.TryGetValue(id, out var w) ? w : 0; } ``` This code also compiles on 6000.5, but the field isn't serialized there. A dictionary-based asset authored in 6.6 **silently loses its data** if a student opens the project in 6.5 or earlier. Pin the course to one editor stream. ## 2.5 Other programming-adjacent 6.6 changes - **Burst is a built-in module.** Its APIs are in `Unity.Burst` with no package install, and its docs moved into the core Scripting API and manual. - **Performance Testing is a core package.** `Unity.PerformanceTesting` APIs are available by default ([[Unity Test Framework]] part 6 installs it as a package). - **Timeline, Cinemachine and Animation Rigging are core packages.** The upgrade guide says projects using **Cinemachine 2 are auto-updated to Cinemachine 3**, which has a different API and data format. Keep a local copy of Cinemachine 2 if you need it. See [[Cinemachine 3]] and [[Timeline Advanced]]. - **YAML change:** word wrapping is disabled in YAML text files, and *Reduce Version Control Noise* is gone (`serializeInlineMappingsOnOneLine` is now a no-op). Expect unrelated-looking YAML diffs, and consider a one-time `ForceReserializeAssets` commit (see [[Version Control]]). - **UI Toolkit:** the legacy UXML Factory/Traits workflow is **removed**, so use `[UxmlElement]` / `[UxmlAttribute]`. `DefaultEventSystem.LegacyInputProcessor` is removed, and `UIToolkitInputConfiguration.SetRuntimeInputBackend` is now a compile error, so just delete the call. - **Rendering Debugger legacy `DebugState` / `DebugUIDrawer` APIs** now fail with `[Obsolete(..., true)]` compile errors. - `Library/Artifacts` is renamed **`Library/DataStore`** in new projects. Update `.gitignore` comments if they mention it. `Library/` is still ignored as a whole. ## Sources - New in Unity 6.6 (Programming, Optimization): https://docs.unity.com/en-us/engine/6000.6/manual/whats-new/unity66 - Upgrade to Unity 6.6 (Programming, Cameras, Editor, UI Toolkit): https://docs.unity.com/en-us/engine/6000.6/manual/upgrade-guides/upgrade-guide-unity66 - C# compiler and language version reference (6000.6): https://docs.unity.com/en-us/engine/6000.6/manual/programming-environment/overview-of-dot-net-in-unity/csharp-compiler - Code reload and the code lifecycle: https://docs.unity.com/en-us/engine/6000.6/manual/programming-environment/code-reload-serialization/code-reload/code-lifecycle - `AutoStaticsCleanupAttribute`: https://docs.unity.com/en-us/engine/6000.6/script-reference/unity/scripting/lifecyclemanagement/autostaticscleanupattribute - Incompatible .NET API reference: https://docs.unity.com/en-us/engine/6000.6/manual/programming-environment/overview-of-dot-net-in-unity/dotnet-incompatible-api - Dictionary serialization: https://docs.unity.com/en-us/engine/6000.6/manual/programming-environment/code-reload-serialization/script-serialization/dictionaries - Path to CoreCLR, 2026: Upgrade Guide (Fast Enter Play Mode, Project Auditor 2.0.0): https://discussions.unity.com/t/path-to-coreclr-2026-upgrade-guide/1714279