Token导航 LogoToken导航TokenDH.com
研究检索只读github未标认证来源可访问许可证需确认审计通过

unity-lifecycleUnity lifecycle 搜索

Agent Skill

unity-lifecycle 用于查找、检索和筛选相关信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要根据关键词、任务场景或来源线索快速定位候选结果时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

306

周安装

13

GitHub Stars

14

下载量

107
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:unity-lifecycle(Unity lifecycle 搜索)
来源仓库:https://github.com/nice-wolf-studio/unity-claude-skills
仓库路径:skills/unity-lifecycle
安装命令:
npx skills add https://github.com/nice-wolf-studio/unity-claude-skills --skill unity-lifecycle
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/nice-wolf-studio/unity-claude-skills --skill unity-lifecycle

简介

用于 Unity 生命周期管理相关信息的查找、检索和筛选,适合在 Codex、Claude、Cursor、Gemini CLI 中快速定位生命周期事件资料。

  • 适用于需要根据关键词或开发场景定位候选结果时使用。
  • 通过 npx skills add 命令从 GitHub 仓库安装并使用。
  • 安装前建议确认权限范围和维护状态,避免触发不必要的联网或文件操作。
  • unity-lifecycle 属于研究检索类 Skill,可作为该场景下的辅助能力补充。

SKILL.md

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 OnValidate for runtime initialization
void OnValidate()
{
    _maxHealth = Mathf.Max(1, _maxHealth);
    _currentHealth = _maxHealth; // This never runs in builds!
}

RIGHT:

// OnValidate: Editor-only, for Inspector feedback and clamping serialized fields
#if UNITY_EDITOR
void OnValidate()
{
    _maxHealth = Mathf.Max(1, _maxHealth);
}
#endif

// Runtime initialization belongs in Awake or Reset
void Awake()
{
    _currentHealth = _maxHealth;
}

// Reset: Editor-only, called when component is first added or Reset from context menu
void Reset()
{
    _maxHealth = 100;
}

GOTCHA: OnValidate is stripped from builds entirely. It runs in the Editor when: a serialized field changes in Inspector, a prefab is modified, or the script recompiles. It does NOT run at play mode start. Calling GetComponent in OnValidate is risky -- the component may not be fully initialized. Wrap side-effect-free validation in #if UNITY_EDITOR.


PATTERN: [ExecuteAlways] Update Timing

WHEN: Using [ExecuteAlways] or [ExecuteInEditMode] for edit-mode behavior

WRONG (Claude default):

[ExecuteAlways]
public class LookAtTarget : MonoBehaviour
{
    [SerializeField] Transform target;

    void Update()
    {
        // Expecting this to run every frame in edit mode
        transform.LookAt(target);
    }
}

RIGHT:

[ExecuteAlways]
public class LookAtTarget : MonoBehaviour
{
    [SerializeField] Transform target;

    void Update()
    {
        // In Edit mode: Update only runs when the Scene view repaints
        // (camera moves, something changes, inspector edited)
        // NOT every frame like Play mode

        if (!target) return; // Safety: references may not exist in edit mode

        #if UNITY_EDITOR
        if (!Application.isPlaying)
        {
            // Edit-mode-specific logic
            transform.LookAt(target);
            return;
        }
        #endif

        // Play-mode logic (runs every frame as normal)
        transform.LookAt(target);
    }
}

GOTCHA: In Edit mode, Update only runs when the Scene view redraws (not per frame). Time.deltaTime is unreliable in Edit mode. Application.isPlaying distinguishes editor from play. [ExecuteAlways] (Unity 2018.3+) is preferred over [ExecuteInEditMode] -- the older attribute has issues with prefab editing in isolation. Components with [ExecuteAlways] must handle null references gracefully since the scene may be partially loaded in edit mode.


PATTERN: [RuntimeInitializeOnLoadMethod] Timing

WHEN: Using static initialization that must run before or after scene load

WRONG (Claude default):

// Assuming it runs before all Awake calls
[RuntimeInitializeOnLoadMethod]
static void Initialize()
{
    // Default timing is AfterSceneLoad -- Awake has ALREADY run!
    Debug.Log("This runs AFTER Awake, not before");
}

RIGHT:

// Explicit timing control
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
static void ResetStaticState()
{
    // Earliest: runs before domain reload completes
    // Use for clearing static fields (critical for Enter Play Mode options)
    _instances.Clear();
}

[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
static void InitBeforeScene()
{
    // Runs before any Awake in the first scene
    // Use for system bootstrap (creating manager objects)
}

[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterSceneLoad)]
static void InitAfterScene()
{
    // Runs after all Awake/OnEnable/Start in the first scene
    // Default if no parameter specified
}

GOTCHA: The full order is: SubsystemRegistration -> AfterAssembliesLoaded -> BeforeSplashScreen -> BeforeSceneLoad -> (scene loads, Awake/OnEnable fire) -> AfterSceneLoad. SubsystemRegistration is critical for clearing static state when using "Enter Play Mode Options" with domain reload disabled.


PATTERN: Script Execution Order

WHEN: One script's initialization depends on another's

WRONG (Claude default):

// Assuming scripts execute in a predictable order
public class GameManager : MonoBehaviour
{
    void Awake() { Instance = this; }
}

public class Player : MonoBehaviour
{
    void Awake()
    {
        GameManager.Instance.Register(this); // May be null if Player.Awake runs first!
    }
}

RIGHT:

// Option 1: [DefaultExecutionOrder] attribute
[DefaultExecutionOrder(-100)] // Negative = runs earlier
public class GameManager : MonoBehaviour
{
    public static GameManager Instance;
    void Awake() { Instance = this; }
}

[DefaultExecutionOrder(0)] // Default
public class Player : MonoBehaviour
{
    void Start() // Use Start for cross-references, not Awake
    {
        GameManager.Instance.Register(this);
    }
}

// Option 2: Awake for self-init, Start for cross-references
// This is the intended pattern -- Awake before Start is guaranteed

GOTCHA: Without explicit ordering, the execution order of the same callback across different scripts is non-deterministic (may vary between builds, platforms, and domain reloads). The Awake-before-Start guarantee exists across ALL scripts, making the Awake=self-init / Start=cross-ref pattern reliable. [DefaultExecutionOrder] is per-class; Project Settings > Script Execution Order is per-class in the Editor.


PATTERN: OnApplicationQuit vs OnDestroy

WHEN: Saving data or cleaning up when the application exits

WRONG (Claude default):

void OnDestroy()
{
    SavePlayerData(); // May fail: other objects might already be destroyed
    // Order of OnDestroy across objects is NOT guaranteed
}

RIGHT:

void OnApplicationQuit()
{
    // Fires BEFORE OnDisable/OnDestroy on all objects
    // All objects still exist and are accessible
    SavePlayerData();
}

void OnDisable()
{
    UnsubscribeFromEvents(); // Still safe during quit sequence
}

void OnDestroy()
{
    // Cleanup own resources only (don't access other objects)
    // No guarantee other objects still exist
    _nativeArray.Dispose();
}

GOTCHA: Quit sequence: OnApplicationQuit (all objects) -> OnDisable (per object) -> OnDestroy (per object). In the Editor, stopping play mode triggers the same sequence. On mobile, OnApplicationQuit may not fire (app backgrounding) -- use OnApplicationPause(true) for mobile save triggers. OnApplicationQuit can be cancelled by setting Application.wantsToQuit = false.


PATTERN: Async Methods + Object Destruction

WHEN: Using async methods in MonoBehaviours

WRONG (Claude default):

async void Start()
{
    await Awaitable.WaitForSecondsAsync(5f);
    // Object may be destroyed by now!
    transform.position = Vector3.zero; // MissingReferenceException
}

RIGHT:

async Awaitable Start()
{
    try
    {
        await Awaitable.WaitForSecondsAsync(5f, destroyCancellationToken);
        transform.position = Vector3.zero; // Safe: would have thrown if destroyed
    }
    catch (OperationCanceledException)
    {
        // Object was destroyed during the wait -- expected, not an error
    }
}

// For methods called from elsewhere:
public async Awaitable DoAsyncWork()
{
    var token = destroyCancellationToken;
    await Awaitable.NextFrameAsync(token);

    // After each await, the token ensures we don't continue on a destroyed object
    token.ThrowIfCancellationRequested();
    _data.Process();
}

GOTCHA: destroyCancellationToken is raised when OnDestroy begins. Always pass it to Awaitable methods. async void methods cannot propagate exceptions -- the app crashes. Use async Awaitable (or async Awaitable<T>) instead, which integrates with Unity's frame loop. See unity-async-patterns skill for deeper async correctness.


Lifecycle Timing Quick Reference

CallbackFires WhenFrequencyScope
AwakeScript instance loads (if GO active)OnceSelf-init
OnEnableComponent/GO enabledEvery enableSubscribe events
StartBefore first Update (if enabled)OnceCross-references
FixedUpdateFixed timestep0-N per framePhysics
UpdateEvery frameOnce per frameGame logic
LateUpdateAfter all UpdatesOnce per frameCamera, follow
OnDisableComponent/GO disabledEvery disableUnsubscribe events
OnDestroyObject destroyedOnceCleanup own resources
OnApplicationQuitApp exitingOnceSave data
OnValidateInspector change (EDITOR ONLY)ManyClamp fields
ResetComponent added/reset (EDITOR ONLY)ManualDefault values

Related Skills

  • unity-scripting -- MonoBehaviour lifecycle diagram, coroutine lifecycle, Awaitable API
  • unity-foundations -- GameObject activation, component enable/disable API
  • unity-async-patterns -- Deep async/await correctness patterns

Additional Resources

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

34.71%
按下载量换算37

Claude

33.99%
按下载量换算36

Cursor

17.95%
按下载量换算19

Gemini CLI

10.25%
按下载量换算11

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

只读

该 Skill 主要提供规则、说明或参考内容,本身偏只读;真正读写文件、联网或执行命令仍取决于宿主 Agent 的任务。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills