Token导航 LogoToken导航

Agent Skill · 开发

unity-async-patterns(Unity async 模式)

unity-async-patterns 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态、代码变更或协作事项进行整理时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

unity-async-patterns 是开发类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为需要联网;许可证信息还不明确,第三方扫描已通过,按安装量在开发类的 21,746 个 Skill 里排第 18,808。

总安装 315周安装 13GitHub Stars 14下载 103核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
unknown

安装方式

通过对话安装

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

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

命令行安装

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

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

这个 Skill 是做什么的

开发类 Skill 面向写代码、改代码和排查问题,一般会读写仓库文件,部分还会执行构建或测试命令。

用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息。适合在需要围绕仓库状态、代码变更或协作事项进行整理时使用。可结合来源仓库和原始 README 核验具体用法。安装前建议确认权限范围、维护状态及是否会触发联网或文件读写。

unity-async-patterns 属于开发类 Skill,可作为该场景下的辅助能力补充。

来源仓库内路径:skills/unity-async-patterns

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/nice-wolf-studio/unity-claude-skills --skill u…;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它需要需要联网,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

unity-async-patterns 怎么安装?

在终端执行 npx skills add https://github.com/nice-wolf-studio/unity-claude-skills --skill unity-async…。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

unity-async-patterns 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

unity-async-patterns 需要什么权限?

权限级别是需要联网。该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

unity-async-patterns 是免费的吗?

公开资料没有标注明确许可证,收费和商用限制都无法确认。正式使用前请到来源仓库核对授权说明。

unity-async-patterns 用的人多吗?

公开数据是累计安装 315 次,近一周安装 13 次,下载 103 次,GitHub 14 星。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

unity-async-patterns 安全吗?

第三方扫描结果为通过,但这只覆盖已知的静态检查项,不能替代自己读一遍源码和安装命令。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。
  • 第三方扫描已通过,常见的高风险行为没有命中。

先想清楚的地方

  • 许可证没有明确标注,能不能商用、能不能再分发都不确定。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理开发类任务、又不想每次都手写提示词的人。

不太适合

  • 需要明确授权才能用到公司项目里的场景。
  • 需要厂商级技术支持和 SLA 的生产系统。

开发类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
skill-vetter

技能审查员 · OpenClaw

8,779,018986操作浏览器MIT-0通过
ontology

本体论 · OpenClaw

6,636,960576只读MIT-0通过
entra-app-registration

内部应用程序注册 · Codex、Claude

6,631,872764接触敏感数据未明确通过
entra-app-registration

内部应用程序注册 · Codex、Claude

3,757,680201接触敏感数据未明确通过
nano-banana-pro

纳米香蕉专业版 · OpenClaw

3,526,898364接触敏感数据MIT-0有提醒
unity-async-patterns

Unity async 模式 · 本页

31514需要联网未明确通过

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文

Async & Coroutine Patterns -- Correctness Patterns

Prerequisite skills: unity-scripting (coroutines, Awaitable API, yield types), unity-lifecycle (destruction timing, destroyCancellationToken)

These patterns target async bugs that are especially dangerous because they often work during testing and fail in production: exceptions silently swallowed, objects destroyed mid-await, and thread context violations.


PATTERN: Awaitable Double-Await

WHEN: Storing an Awaitable instance and awaiting it more than once

WRONG (Claude default):

Awaitable task = Awaitable.WaitForSecondsAsync(2f);
await task; // First await -- works
await task; // Second await -- UNDEFINED BEHAVIOR (may complete instantly or throw)

RIGHT:

// Awaitable is POOLED -- after the first await completes, the instance is recycled
// Each Awaitable should be awaited exactly once

// If you need to await the same operation from multiple places, use .AsTask():
var task = Awaitable.WaitForSecondsAsync(2f).AsTask();
await task; // Works
await task; // Works -- Task is not pooled

// Or simply create separate Awaitables:
await Awaitable.WaitForSecondsAsync(2f);
await Awaitable.WaitForSecondsAsync(2f); // Fresh instance

GOTCHA: Unity pools Awaitable instances to avoid allocation. After completion, the instance is returned to the pool and may be reused by a completely different operation. A second await on the same instance may see a different operation's state, complete instantly, or throw. This is unlike Task which can be safely awaited multiple times. Use .AsTask() when you need multi-await semantics, but be aware this allocates.


PATTERN: Missing destroyCancellationToken

WHEN: Writing async methods in MonoBehaviours

WRONG (Claude default):

async Awaitable Start()
{
    await Awaitable.WaitForSecondsAsync(5f);
    // If object was destroyed during the wait:
    // - MissingReferenceException on next Unity API call
    // - Or worse: silently operates on a "fake-null" object
    transform.position = Vector3.zero;
}

RIGHT:

async Awaitable Start()
{
    try
    {
        await Awaitable.WaitForSecondsAsync(5f, destroyCancellationToken);
        transform.position = Vector3.zero;
    }
    catch (OperationCanceledException)
    {
        // Object was destroyed -- this is expected, not an error
    }
}

// For methods that chain multiple awaits:
async Awaitable DoMultiStepWork()
{
    var token = destroyCancellationToken;

    await Awaitable.NextFrameAsync(token);
    ProcessStep1();

    await Awaitable.WaitForSecondsAsync(1f, token);
    ProcessStep2(); // Safe: would have thrown before reaching here if destroyed

    await LoadAssetAsync(token);
    ProcessStep3();
}

GOTCHA: destroyCancellationToken is a property on MonoBehaviour that triggers when OnDestroy begins. Every Awaitable wait method accepts an optional CancellationToken. Without it, the await completes normally even after the object is destroyed, leading to MissingReferenceException. Always pass the token AND catch OperationCanceledException.


PATTERN: Thread Context After BackgroundThreadAsync

WHEN: Returning to Unity APIs after doing work on a background thread

WRONG (Claude default):

async Awaitable ProcessData()
{
    await Awaitable.BackgroundThreadAsync();
    var result = HeavyComputation(); // OK: runs on background thread

    // CRASH: Accessing Unity API from background thread
    transform.position = new Vector3(result, 0, 0);
}

RIGHT:

async Awaitable ProcessData()
{
    await Awaitable.BackgroundThreadAsync();
    var result = HeavyComputation(); // Runs on background thread

    await Awaitable.MainThreadAsync(); // Switch BACK to main thread
    transform.position = new Vector3(result, 0, 0); // Now safe

    // Can switch back and forth:
    await Awaitable.BackgroundThreadAsync();
    var moreData = AnotherHeavyTask();

    await Awaitable.MainThreadAsync();
    ApplyResults(moreData);
}

GOTCHA: After BackgroundThreadAsync(), ALL subsequent code runs on a thread pool thread until you explicitly switch back with MainThreadAsync(). Unity APIs (Transform, GameObject, Physics, etc.) are not thread-safe and will throw or corrupt state if called from a background thread. MainThreadAsync() resumes on the next frame's player loop update, not immediately.


PATTERN: Coroutine Error Swallowing

WHEN: Exceptions occur inside coroutines

WRONG (Claude default):

IEnumerator LoadAndProcess()
{
    yield return LoadData(); // If this throws, coroutine silently stops
    ProcessData();           // Never reached, no error in console (or just a log, no stack)
}

// try/catch doesn't work with yield:
IEnumerator BadErrorHandling()
{
    try
    {
        yield return SomethingDangerous(); // COMPILER ERROR: cannot yield in try block with catch
    }
    catch (Exception e)
    {
        Debug.LogError(e);
    }
}

RIGHT:

// Option 1: Use Awaitable instead (proper exception propagation)
async Awaitable LoadAndProcess()
{
    try
    {
        await LoadDataAsync();
        ProcessData();
    }
    catch (Exception e)
    {
        Debug.LogError($"Load failed: {e}");
    }
}

// Option 2: Error handling without yield in the try block
IEnumerator LoadAndProcessCoroutine()
{
    bool success = false;
    Exception error = null;

    // Wrap the yield outside try/catch
    yield return LoadDataCoroutine(result =>
    {
        success = true;
    });

    // Handle errors after the yield
    if (!success)
    {
        Debug.LogError("Load failed");
        yield break;
    }

    ProcessData();
}

GOTCHA: In coroutines, yield return cannot appear inside a try block that has a catch clause (C# language restriction). Exceptions in yielded coroutines are logged to the console but execution silently stops -- no propagation to the caller. The caller's coroutine continues as if the nested one completed. Use Awaitable for any operation that can fail and needs error handling.


PATTERN: WaitForEndOfFrame in Batch Mode

WHEN: Using WaitForEndOfFrame or Awaitable.EndOfFrameAsync in headless/server/test environments

WRONG (Claude default):

IEnumerator CaptureScreenshot()
{
    yield return new WaitForEndOfFrame(); // HANGS in batch mode (no rendering)
    var tex = ScreenCapture.CaptureScreenshotAsTexture();
}

// Same issue with Awaitable:
async Awaitable WaitForRender()
{
    await Awaitable.EndOfFrameAsync(); // HANGS in batch mode
}

RIGHT:

IEnumerator CaptureScreenshot()
{
    // Check if we're in batch mode
    if (Application.isBatchMode)
    {
        yield return null; // Just wait one frame instead
        Debug.LogWarning("Screenshot not available in batch mode");
        yield break;
    }

    yield return new WaitForEndOfFrame();
    var tex = ScreenCapture.CaptureScreenshotAsTexture();
}

// For tests that need frame advancement without rendering:
IEnumerator TestCoroutine()
{
    yield return null; // Advances one frame (works in all modes)
    // yield return new WaitForFixedUpdate(); // Also works in batch mode
}

GOTCHA: WaitForEndOfFrame and EndOfFrameAsync wait for the rendering phase. In batch mode (-batchmode flag), headless servers, and some test runners, there is no rendering -- so these yields never complete and the coroutine/async hangs forever. Use yield return null (next Update) or Awaitable.NextFrameAsync() for frame advancement that works everywhere.


PATTERN: Nested Coroutine Cancellation

WHEN: Stopping a parent coroutine that launched child coroutines

WRONG (Claude default):

Coroutine _mainRoutine;

void Start()
{
    _mainRoutine = StartCoroutine(MainLoop());
}

IEnumerator MainLoop()
{
    StartCoroutine(SubTaskA()); // Launched independently
    StartCoroutine(SubTaskB()); // Launched independently
    yield return new WaitForSeconds(10f);
}

void Cancel()
{
    StopCoroutine(_mainRoutine);
    // SubTaskA and SubTaskB continue running!
}

RIGHT:

private Coroutine _mainRoutine;
private Coroutine _subA;
private Coroutine _subB;

IEnumerator MainLoop()
{
    _subA = StartCoroutine(SubTaskA());
    _subB = StartCoroutine(SubTaskB());
    yield return new WaitForSeconds(10f);
}

void Cancel()
{
    // Must stop each coroutine individually
    if (_mainRoutine != null) StopCoroutine(_mainRoutine);
    if (_subA != null) StopCoroutine(_subA);
    if (_subB != null) StopCoroutine(_subB);
}

// Better: yield return child coroutines (parent owns them)
IEnumerator MainLoopBetter()
{
    yield return StartCoroutine(SubTaskA()); // Waits for A, then...
    yield return StartCoroutine(SubTaskB()); // Waits for B
    // Stopping MainLoopBetter also stops the currently-yielded child
}

GOTCHA: StartCoroutine(SubTask()) launches an independent coroutine. StopCoroutine only stops the specified coroutine. BUT: yield return StartCoroutine(SubTask()) makes the parent wait for the child, and stopping the parent also stops the yielded child. The key distinction: StartCoroutine without yield return = fire-and-forget; with yield return = owned by parent. For complex cancellation trees, prefer Awaitable with CancellationToken.


PATTERN: async void vs async Awaitable

WHEN: Declaring async methods in Unity scripts

WRONG (Claude default):

// async void: exceptions crash the application with no way to catch them
async void DoWork()
{
    await Awaitable.WaitForSecondsAsync(1f);
    throw new Exception("oops"); // UNHANDLED -- crashes the app
}

void Start()
{
    DoWork(); // No way to catch the exception from here
}

RIGHT:

// async Awaitable: proper exception propagation
async Awaitable DoWork()
{
    await Awaitable.WaitForSecondsAsync(1f);
    throw new Exception("oops"); // Propagates to caller
}

async Awaitable Start()
{
    try
    {
        await DoWork(); // Exception caught here
    }
    catch (Exception e)
    {
        Debug.LogError($"Work failed: {e.Message}");
    }
}

// async void is ONLY acceptable for Unity event handlers that require void:
// - Button.onClick handlers
// - UnityEvent callbacks
// Even then, wrap the body in try/catch:
async void OnButtonClicked()
{
    try
    {
        await SaveGameAsync();
    }
    catch (Exception e)
    {
        Debug.LogError(e);
    }
}

GOTCHA: async void methods propagate exceptions to the SynchronizationContext, which in Unity logs them and potentially crashes. async Awaitable methods propagate exceptions to the awaiter, allowing proper try/catch. Unity's lifecycle methods (Start, OnEnable, etc.) can return Awaitable -- prefer this over void when using async.


PATTERN: Concurrent Awaitable Race Conditions

WHEN: Multiple async operations modify shared state

WRONG (Claude default):

// Two async methods writing to the same field
async Awaitable OnClickSearch(string query)
{
    var results = await SearchAsync(query); // User types "cat"
    _displayedResults = results;            // Race: which query wins?
}
// User clicks twice quickly: "cat" then "dog"
// If "dog" returns first, "cat" results overwrite "dog" results

RIGHT:

private CancellationTokenSource _searchCts;

async Awaitable OnClickSearch(string query)
{
    // Cancel the previous search
    _searchCts?.Cancel();
    _searchCts?.Dispose();
    _searchCts = new CancellationTokenSource();
    var token = _searchCts.Token;

    try
    {
        var results = await SearchAsync(query, token);
        token.ThrowIfCancellationRequested(); // Check before applying
        _displayedResults = results;          // Only the latest search applies
    }
    catch (OperationCanceledException)
    {
        // Previous search cancelled -- expected
    }
}

void OnDestroy()
{
    _searchCts?.Cancel();
    _searchCts?.Dispose();
}

GOTCHA: Unlike coroutines (which are single-threaded and frame-sequential), multiple Awaitable chains can interleave across frames. The cancel-previous pattern ensures only the most recent operation applies its results. Link the CancellationTokenSource token with destroyCancellationToken using CancellationTokenSource.CreateLinkedTokenSource(destroyCancellationToken) for automatic cleanup on destroy.


PATTERN: Addressables AsyncOperationHandle Leak

WHEN: Loading assets with Addressables and not releasing them

WRONG (Claude default):

async Awaitable LoadEnemy()
{
    var handle = Addressables.LoadAssetAsync<GameObject>("enemy_prefab");
    var prefab = await handle.Task;
    Instantiate(prefab);
    // Handle never released -- memory leak!
}

RIGHT:

private AsyncOperationHandle<GameObject> _enemyHandle;

async Awaitable LoadEnemy()
{
    _enemyHandle = Addressables.LoadAssetAsync<GameObject>("enemy_prefab");
    var prefab = await _enemyHandle.Task;
    Instantiate(prefab);
}

void OnDestroy()
{
    // Release when no longer needed
    if (_enemyHandle.IsValid())
        Addressables.Release(_enemyHandle);
}

// For instantiated objects, use Addressables.InstantiateAsync (auto-tracked):
async Awaitable SpawnEnemy()
{
    var handle = Addressables.InstantiateAsync("enemy_prefab", spawnPoint.position, Quaternion.identity);
    var instance = await handle.Task;
    // When done: Addressables.ReleaseInstance(instance) instead of Destroy
}

GOTCHA: Every Addressables.LoadAssetAsync call increments a reference count. Without Addressables.Release, the asset stays in memory forever. Addressables.InstantiateAsync tracks instances automatically -- use Addressables.ReleaseInstance instead of Destroy. Scene loading with Addressables (LoadSceneAsync) auto-releases on scene unload. Releasing a handle with active instances may cause pink/missing material rendering.


PATTERN: UniTask vs Awaitable Selection

WHEN: Choosing an async framework for a Unity project

WRONG (Claude default):

// Mixing UniTask and Awaitable in the same method
async UniTask DoWork()
{
    await Awaitable.NextFrameAsync(); // Type mismatch: Awaitable in UniTask method
}

RIGHT:

// Pick ONE async framework per project:

// === Option A: Awaitable (Unity 6+ built-in) ===
// Pros: No dependencies, integrated with Unity lifecycle, pooled (zero-alloc)
// Cons: Limited utilities (no WhenAll, WhenAny, no channel/queue)
async Awaitable DoWorkAwaitable()
{
    await Awaitable.NextFrameAsync(destroyCancellationToken);
    await Awaitable.WaitForSecondsAsync(1f, destroyCancellationToken);
}

// === Option B: UniTask (third-party: com.cysharp.unitask) ===
// Pros: Rich API (WhenAll, WhenAny, channels), PlayerLoop integration, zero-alloc
// Cons: External dependency, must learn UniTask-specific patterns
async UniTask DoWorkUniTask()
{
    await UniTask.NextFrame(cancellationToken: destroyCancellationToken);
    await UniTask.Delay(1000, cancellationToken: destroyCancellationToken);
    // UniTask extras: WhenAll, WhenAny, Channel, AsyncReactiveProperty
}

// Converting between them (if mixing is unavoidable):
// Awaitable -> UniTask: not directly; use .AsTask() as bridge
// UniTask -> Awaitable: not directly; use .AsTask() as bridge

GOTCHA: Awaitable is built into Unity 6+ and requires no packages. UniTask (com.cysharp.unitask) is a mature third-party library with richer functionality. Do NOT mix both in the same codebase without a clear boundary -- their cancellation patterns, pooling behavior, and PlayerLoop integration differ. If targeting Unity 6+, Awaitable covers most needs. Use UniTask if you need advanced patterns like WhenAll, async LINQ, or IUniTaskAsyncEnumerable.


Anti-Patterns Quick Reference

Anti-PatternProblemFix
await Task.Delay() in UnityIgnores TimeScale, no frame syncUse Awaitable.WaitForSecondsAsync()
Task.Run() for Unity computationThread pool with no main thread returnUse Awaitable.BackgroundThreadAsync() + MainThreadAsync()
StopAllCoroutines() as cleanupNuclear option; stops coroutines you didn't startTrack and stop specific coroutines
Ignoring return value of StartCoroutineCannot cancel laterStore the Coroutine reference
yield return new WaitForSeconds(0)Unclear intent, allocatesUse yield return null (no allocation)
async Task methods in MonoBehaviourTask exceptions lost, no destroyCancellationToken integrationUse async Awaitable

Related Skills

  • unity-scripting -- Coroutine fundamentals, Awaitable API reference, yield types
  • unity-lifecycle -- destroyCancellationToken, object destruction timing
  • unity-performance -- Async profiling, allocation tracking

Additional Resources

平台分布

Codex

38.64%
按下载量换算40

Claude

29.57%
按下载量换算30

Cursor

20.41%
按下载量换算21

Gemini CLI

9.05%
按下载量换算9

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

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

继续浏览同类 Skills