unity-lifecycle
Unity lifecycle and execution order correctness patterns. Catches common mistakes with initialization ordering, destruction timing, fake-null, disabled components, editor vs runtime init, DontDestroyOnLoad, and async destruction. PATTERN format: WHEN/WRONG/RIGHT/GOTCHA. Based on Unity 6.3 LTS documentation.
Nice-Wolf-Studio · 已有静态检查记录
安装与使用
运行命令前先阅读来源与依赖说明。复制命令不会自动安装或执行。
npx skills add Nice-Wolf-Studio/unity-claude-skills --skill unity-lifecycle技能说明
name: unity-lifecycle description: > Unity lifecycle and execution order correctness patterns. Catches common mistakes with initialization ordering, destruction timing, fake-null, disabled components, editor vs runtime init, DontDestroyOnLoad, and async destruction. PATTERN format: WHEN/WRONG/RIGHT/GOTCHA. Based on Unity 6.3 LTS documentation. globs:
- "**/*.cs"
Unity Lifecycle & Execution Order -- Correctness Patterns
Prerequisite skills:
unity-scripting(MonoBehaviour lifecycle, coroutines),unity-foundations(GameObjects, components)
These patterns target initialization bugs, null reference exceptions from destruction timing, and subtle editor-vs-runtime differences that cause "works in editor, fails in build" issues.
PATTERN: Fake-Null Trap (?. and ?? on Destroyed Objects)
WHEN: Null-checking Unity objects that may have been destroyed
WRONG (Claude default):
// C# null-conditional and null-coalescing bypass Unity's == override
myComponent?.DoSomething(); // May call method on destroyed object!
var fallback = myComponent ?? other; // May return a destroyed "fake-null" object!
RIGHT:
// Unity overrides == to return true for destroyed objects
// Always use == null or implicit bool conversion
if (myComponent != null)
myComponent.DoSomething();
// Or use the implicit bool operator (equivalent to != null for UnityEngine.Object)
if (myComponent)
myComponent.DoSomething();
GOTCHA: When Unity destroys an object, the C# reference still exists but Unity marks it as "fake-null". The == operator is overridden to handle this, but ?., ??, is null, and is not null use the C# native null check and see a valid (non-null) reference. This is the #1 source of MissingReferenceException. Pattern matching (obj is MyType t) also bypasses the override -- use if (obj != null && obj is MyType t).
PATTERN: Destroy is Deferred
WHEN: Destroying objects and accessing them in the same frame
WRONG (Claude default):
// Expecting immediate removal
Destroy(enemy);
enemies.Remove(enemy); // enemy still exists this frame
Debug.Log(enemies.Count); // Count is correct, but enemy is "alive" until end of frame
// Iterating and destroying
foreach (var e in enemies)
if (e.health <= 0)
Destroy(e.gameObject); // Modifying collection during iteration = crash
RIGHT:
// Destroy happens at END of current frame (after all Updates complete)
Destroy(enemy);
// enemy is still accessible this frame, but == null returns true
// Safe iteration: collect then destroy
var toDestroy = enemies.Where(e => e.health <= 0).ToList();
foreach (var e in toDestroy)
{
enemies.Remove(e);
Destroy(e.gameObject);
}
// If you truly need immediate destruction (EDITOR ONLY):
// DestroyImmediate(obj); // Never use in runtime code
GOTCHA: Destroy schedules destruction for end of frame. The object's == null check returns true immediately after Destroy(), but OnDisable and OnDestroy run later. DestroyImmediate is synchronous but only safe in editor scripts -- using it at runtime causes hard-to-debug ordering issues. Destroy(obj, delay) waits delay seconds before scheduling destruction.
PATTERN: Disabled Component Still Gets Awake
WHEN: A component starts with its checkbox unchecked in the Inspector
WRONG (Claude default):
// Assuming Awake is skipped for disabled components
// "My Awake runs even though the component is disabled -- bug?"
RIGHT:
// Awake ALWAYS runs if the GAMEOBJECT is active (regardless of component enabled state)
// Start is SKIPPED if the component is disabled at Start time
// Start runs later when the component is first enabled
void Awake()
{
// This runs even if this component is disabled
// Use for self-initialization (cache references, set defaults)
_rb = GetComponent<Rigidbody>();
}
void Start()
{
// This is DEFERRED until the component is first enabled
// Use for cross-references that depend on other objects being initialized
_target = FindObjectOfType<Player>();
}
void OnEnable()
{
// Runs every time the component is enabled (including the first time)
// Runs AFTER Awake but BEFORE Start on first enable
SubscribeToEvents();
}
GOTCHA: The key distinction: Awake depends on GameObject active state. Start and OnEnable depend on component enabled state. If the GameObject starts inactive (SetActive(false)), neither Awake nor Start runs until the GameObject is activated. Once the GameObject activates: Awake fires immediately, OnEnable fires if component is enabled, Start fires on the next frame if component is enabled.
PATTERN: OnEnable/OnDisable for Event Subscription
WHEN: Subscribing to events, delegates, or Unity callbacks
WRONG (Claude default):
void Start()
{
EventManager.OnPlayerDied += HandlePlayerDied;
}
void OnDestroy()
{
EventManager.OnPlayerDied -= HandlePlayerDied;
}
// BUG: If object is disabled/re-enabled, events accumulate
// BUG: If scene reloads, Start doesn't re-run for DontDestroyOnLoad objects
RIGHT:
void OnEnable()
{
EventManager.OnPlayerDied += HandlePlayerDied;
SceneManager.sceneLoaded += OnSceneLoaded;
}
void OnDisable()
{
EventManager.OnPlayerDied -= HandlePlayerDied;
SceneManager.sceneLoaded -= OnSceneLoaded;
}
// Correctly handles: disable/enable cycles, scene reloads, destruction
GOTCHA: OnEnable/OnDisable are the symmetric pair. They fire on: component enable/disable, GameObject activate/deactivate, scene load/unload, AND before OnDestroy. Using Start/OnDestroy fails when objects are pooled (disabled/enabled without destruction) or when DontDestroyOnLoad objects persist across scene reloads.
PATTERN: OnValidate is Editor-Only
WHEN: Using OnValidate to initialize or validate component state
WRONG (Claude default):
// Relying on OnValidat
阅读完整来源 ↗