gamedev-unity/skills/unity-skills/skills/unitask-design/SKILL.md
Source-anchored design rules for Cysharp UniTask 2.5.10 (Unity 2018.4+) — struct semantics, PlayerLoop timing, cancellation, composition, conversion, async enumerables, triggers, and pitfalls. Use when writing or reviewing async UniTask code, choosing PlayerLoopTiming, handling CancellationToken, or composing WhenAll/WhenAny, even if the user just says "异步" or "零分配async". 为 Cysharp UniTask 2.5.10(Unity 2018.4+)提供源码锚定的设计规则(struct 语义、PlayerLoop 时机、取消、组合、转换、异步流、触发器、陷阱);当用户要编写或审查 async UniTask 代码、选择 PlayerLoopTiming、处理 CancellationToken、或组合 WhenAll/WhenAny 时使用。
npx skillsauth add bernatmv/ai-rules unity-unitask-designInstall this skill globally with one command. Works with Claude Code, Cursor, and Windsurf.
3 of 9 scanners reported clean
Some scanners were skipped, did not run, or reported a non-clean status. Review each row below.
Advisory module. Every rule is distilled from Cysharp UniTask source at:
[email protected] (Unity 2018.4 baseline; actively used with 2022.3 / Unity 6)Each rule cites a concrete file/line so the reasoning is auditable and the AI does not improvise against stale memory.
Mode: Documentation only — no REST skills to gate; load freely under any operating mode (Approval / Auto / Bypass).
Load before writing or reviewing any of:
async UniTask / async UniTask<T> / async UniTaskVoid method signature.Forget(), .AttachExternalCancellation(token), .SuppressCancellationThrow() chainingUniTask.Yield, UniTask.NextFrame, UniTask.Delay, UniTask.WaitForEndOfFrame, UniTask.WaitForFixedUpdateUniTask.WaitUntil, UniTask.WaitWhile, UniTask.WaitUntilValueChanged, UniTask.WaitUntilCanceledUniTask.WhenAll, UniTask.WhenAny, UniTask.WhenEachUniTask.SwitchToMainThread, UniTask.SwitchToThreadPool, UniTask.RunAsyncOperation.ToUniTask(), UnityWebRequest.SendWebRequest().ToUniTask(), Coroutine.ToUniTask()this.GetCancellationTokenOnDestroy(), GetAsyncStartTrigger() and other AsyncTrigger* extensionsUniTaskCompletionSource / UniTaskCompletionSource<T> manual completion sourcesIUniTaskAsyncEnumerable<T> / UniTaskAsyncEnumerable / AsyncReactiveProperty<T> / Channel<T>Task.Run / SwitchToThreadPool are forbidden| # | Rule | Source anchor |
|---|------|---------------|
| 1 | UniTask is a readonly partial struct (value type). Once awaited, its IUniTaskSource is recycled; awaiting the same UniTask variable twice throws. Use .Preserve() to obtain a memoized copy that can be awaited multiple times. | UniTask.cs:34, UniTask.cs:103-113 |
| 2 | A UniTask returned by a method must be either awaited, .Forget()ed, or .AttachExternalCancellation(token)ed. Orphan UniTasks silently swallow exceptions into UniTaskScheduler.UnobservedTaskException. | UniTaskScheduler.cs:13, UniTaskVoid.cs:11-17 |
| 3 | PlayerLoopTiming defines 16 timing slots (2020.2+; 14 on older Unity). Default UniTask.Yield() / UniTask.Delay uses PlayerLoopTiming.Update. Mixing LastPostLateUpdate with legacy WaitForEndOfFrame coroutines changes observed frame ordering. | PlayerLoopHelper.cs:71-99 |
| 4 | UniTask.Delay(int ms, DelayType, PlayerLoopTiming, CancellationToken, bool cancelImmediately) accepts DelayType.DeltaTime / UnscaledDeltaTime / Realtime. The old bool ignoreTimeScale overload still exists but mixes semantics — prefer the DelayType overload for new code. | UniTask.Delay.cs:12-20, UniTask.Delay.cs:147-165 |
| 5 | this.GetCancellationTokenOnDestroy() is defined for MonoBehaviour, GameObject, and Component in AsyncTriggerExtensions. Plain C# classes do NOT receive this extension — they must own a CancellationTokenSource explicitly. | Triggers/AsyncTriggerExtensions.cs:14,22,28 |
| 6 | UniTask.WhenAll(params UniTask[] tasks) and the IEnumerable<UniTask> overload both exist. Semantically match Task.WhenAll but are zero-alloc when tasks are UniTask-native. WhenAny returns (winnerIndex, result) tuple for UniTask<T>. | UniTask.WhenAll.cs:12,22,31,41, UniTask.WhenAny.cs |
| 7 | AsyncOperation.ToUniTask(IProgress<float>, PlayerLoopTiming, CancellationToken) is the canonical adapter. await operation works too but silently leaks the progress callback if you also set operation.completed += …. | UnityAsyncExtensions.cs |
| 8 | UniTaskCompletionSource and UniTaskCompletionSource<T> support TrySetResult / TrySetException / TrySetCanceled. Once any of the three succeeds, subsequent calls return false — they do not throw. | UniTaskCompletionSource.cs:573,610,754,792 |
| 9 | UniTask.SwitchToThreadPool() and UniTask.Run(...) are compile-time available on all platforms BUT throw NotSupportedException at runtime on WebGL. Guard with #if !UNITY_WEBGL || UNITY_EDITOR or fall back to UniTask.Yield()-based cooperative work. | UniTask.Threading.cs:57 |
| 10 | Returning async UniTaskVoid is the fire-and-forget idiom that lets await be used INSIDE the method. async void methods cannot return UniTask — a common compile error when porting from Task. | UniTaskVoid.cs:11-17, UniTask.Factory.cs:112-131 |
| Sub-doc | When to read |
|---------|--------------|
| BASICS.md | UniTask vs Task differences, struct semantics, UniTaskVoid, zero-alloc state machine, AsyncUniTaskMethodBuilder |
| PLAYERLOOP.md | 16-value PlayerLoopTiming table, Yield/NextFrame/Delay/WaitForEndOfFrame/WaitForFixedUpdate, DelayType, frame-ordering with legacy coroutines |
| CANCELLATION.md | CancellationToken patterns, GetCancellationTokenOnDestroy (3 overloads), AttachExternalCancellation, CancelAfterSlim, AddTo, OperationCanceledException flow |
| COMPOSITION.md | WhenAll, WhenAny, WhenEach, Forget, SuppressCancellationThrow, ContinueWith, timeout patterns |
| CONVERSION.md | AsyncOperation.ToUniTask, UnityWebRequest.SendWebRequest().ToUniTask, IEnumerator.ToUniTask, Task.AsUniTask, UniTask.AsTask, UniTask.ToCoroutine |
| ASYNCENUMERABLE.md | IUniTaskAsyncEnumerable<T>, UniTaskAsyncEnumerable, AsyncReactiveProperty<T>, Channel<T>, EveryValueChanged, Publish, LINQ-to-async operators |
| TRIGGERS.md | AsyncTriggerBase, GetAsyncStartTrigger, GetAsyncDestroyTrigger, OnCollisionEnterAsync, OnClickAsync, MonoBehaviourMessagesTriggers, lifecycle cancellation |
| PITFALLS.md | 30 concrete hallucination / runtime pitfalls (double-await, forgotten Forget, WebGL threadpool, tracker memory, wrong PlayerLoopTiming, coroutine interop bugs) |
UniTask, raw Task, and IEnumerator at the architecture layer → load asynctween.ToUniTask(TweenCancelBehaviour, token)) → load dotween-designhandle.ToUniTask() extension → load yooasset-designAsyncOperationHandle.ToUniTask() rules → load addressables-designCysharp.Threading.Tasks.asmdef reference) → load asmdefTargets UniTask 2.5.10. Earlier 2.x versions are mostly source-compatible; key differences:
WaitForEndOfFrame(MonoBehaviour coroutineRunner) overload added in recent 2.x — on 2023.1+ a parameterless overload is available (#if UNITY_2023_1_OR_NEWER). See UniTask.Delay.cs:78-103.UniTask.WhenEach is a newer addition; not all 2.x builds ship it.When in doubt, read the cited source — not your memory.
development
Keyword research and validation with real search-demand data — never ship keywords from intuition alone. Probes Google Autocomplete per language (free, no account) to prove demand and discover the exact phrasing people type, checks SERPs for winnability, and uses Keyword Planner/Ahrefs/Semrush exports when the user has access. Activates when: choosing or reviewing SEO keywords, meta keywords, page titles, article topics or slugs, landing page copy targeting search, App Store/ASO keyword fields, multilingual keyword sets, 'what should we rank for', 'keyword analysis', or auditing why a page doesn't rank. Also invoke it as a validation pass whenever another skill or task produces a keyword list.
development
Automate YooAsset hot-update and asset bundles — build bundles, run Editor simulate builds, manage Collector groups, analyze BuildReport, and validate runtime. Use when building or simulating YooAsset bundles, configuring collectors, or validating hot-update assets, even if the user just says "热更" or "打AB包". 自动化 YooAsset 热更新与资源包(构建 bundle、编辑器模拟构建、管理 Collector 分组、分析 BuildReport、运行时校验);当用户要构建或模拟 YooAsset 资源包、配置 collector、或校验热更资源时使用。
development
Source-anchored design rules for YooAsset v2.3.18 — initialization, default-package shortcuts, play modes, asset handles, loading, updates, filesystem, build, and pitfalls. Use when writing or reviewing YooAsset code, initializing packages, loading assets via handles, setting up hot-update/download, or choosing a play mode, even if the user just says "热更" or "资源包". 为 YooAsset v2.3.18 提供源码锚定的设计规则(初始化、默认包快捷方式、运行模式、资源句柄、加载、更新、文件系统、构建、陷阱);当用户要编写或审查 YooAsset 代码、初始化 package、用句柄加载资源、配置热更/下载、或选择运行模式时使用。
data-ai
Last-resort guidance for safely hand-editing Unity serialized YAML (.unity/.prefab/.asset/.meta/ProjectSettings) — reference/fileID repair, GUID safety, and merge-conflict fixes. Use when REST cannot reach the change and YAML must be hand-edited — fixing m_Script GUIDs, broken fileID references, .meta files, or merge conflicts, even if the user just says "场景文件打不开" or "引用丢了". 安全手编 Unity 序列化 YAML(.unity/.prefab/.asset/.meta/ProjectSettings)的最后手段(引用/fileID 修复、GUID 安全、合并冲突修复);当 REST 无法触达、必须手编 YAML 时使用——修复 m_Script GUID、断裂 fileID 引用、.meta 文件或合并冲突。