Logo vun Tools Unity Unitask

Tools Unity Unitask

Communautéit
IdoCohen560
tools-unity-unitask

UniTask async/await patterns for Unity including cancellation, lifecycle binding, and coroutine interop.

Iwwersiicht

EditeurIdoCohen560
Repositoryclaude-unity-game-studio
Skill-Nummtools-unity-unitask
Stären
28
Forks
6
Matgeliwwert Fichieren
Nëmmen Instruktiounen
LizenzMIT
Linken
  • Instruktiounen am Markdown-Format

    Eng SKILL.md-Datei, déi de Modell bei Bedarf luet, soudatt nëmmen Token ufalen, wann eng Ufro tatsächlech dozou passt.

  • Funktionéiert mat all LLM

    KI-Skills si reng Markdown, keen ubidderspezifesche Code. Dofir funktionéiert dëse Skill mat GPT, Claude, Gemini, Grok oder engem lokale Modell.

  • Alles an den Instruktiounen

    Alles, wat de Modell brauch, steet an den Instruktiounen — keng zousätzlech Dateien ze synchroniséieren.

  • Open Source

    Vum IdoCohen560 op GitHub verëffentlecht. Liest de Quelltext, ier Dir de Skill installéiert.

Installatioun

Installéiert de KI-Skill Tools Unity Unitask an TypingMind, fir e mat all LLM ze benotzen, oder füügt en an en anere KI-Agent an, deen SKILL.md liest.

1

An TypingMind installéieren

TypingMind installéiert e Skill direkt aus sengem GitHub-Dossier — dobäi gëtt SKILL.md gelies, d'Ressourcedateie gi gebëndelt an d'Resultat gëtt lokal gespäichert.

  1. Maacht d'App op a gitt op Plugins → Skills.
  2. Wielt „Vun GitHub installéieren“.
  3. Pecht d'URL vum Skill-Dossier hei drënner an a bestätegt.
    https://github.com/IdoCohen560/claude-unity-game-studio/tree/main/examples/my-first-game/.claude/skills/tools-unity-unitask
  4. Aktivéiert de Skill an all Chat, an deem Dir e benotze wëllt.
Plugins → Skills → Skill afügen → Vu GitHub-URL, pecht dann d'URL vum Dossier an a klickt op Weider.
2

An engem anere KI-Agent installéieren

All KI-Agent, deen d'Format Agent Skills liest, kann dëse Skill benotzen — kopéiert den Dossier an de Skill-Verzeechnes vun deem KI-Agent.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/IdoCohen560/claude-unity-game-studio.git /tmp/claude-unity-game-studio
mkdir -p .claude/skills
cp -r /tmp/claude-unity-game-studio/examples/my-first-game/.claude/skills/tools-unity-unitask .claude/skills/tools-unity-unitask
Start Claude Code nom Kopéieren nei, fir datt den neie Skill erkannt gëtt.

An TypingMind benotzen

Aktivéiert Tools Unity Unitask an engem Chat vun TypingMind, an de Modell iwwerhëlt de Rescht. Den Numm an d'Beschreiwung stinn am System-Prompt. Soubal eng Ufro dozou passt, luet de Modell déi komplett Instruktioune selwer — Dir musst de Skill ni manuell opruffen, an et fale keng Token un, bis en tatsächlech benotzt gëtt.

De Modell luet Tools Unity Unitask automatesch, soubal eng Ufro dozou passt.

Funktionéiert mat all KI-Modell

KI-Skills si reng Markdown-Instruktiounen amplaz vun ubidderspezifeschem Code. Dofir ass Tools Unity Unitask net un de Modell gebonnen, fir deen de Skill geschriwwe gouf. Installéiert en eemol an TypingMind a benotzt e mat GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama oder engem lokale Modell, deen Dir selwer bedreift — alles mat Ären eegenen API-Keys.

  • Gëtt nëmme gelueden, wann et néideg ass

    De System-Prompt enthält nëmmen den Numm an d'Beschreiwung. D'Instruktioune gi bei der éischter passender Ufro gelueden, soudatt en onbenotzte Skill näischt kascht.

  • De Modell am lafende Chat wiesselen

    Well de Skill aus Instruktiounen amplaz vu Code besteet, funktionéiert en och no engem Modellwiessel — den nächste Modell liest déi selwecht SKILL.md-Datei.

Skill-Instruktiounen

Dëst ass den Inhalt vu SKILL.md, deen de Modell luet. Liest e virun der Installatioun — e Skill besteet aus Instruktiounen, déi Äre Modell befollegt.

UniTask Async/Await for Unity

Overview

UniTask provides efficient async/await support for Unity with zero allocation, proper cancellation, and Unity lifecycle integration.

When to Use

  • Async operations in Unity (loading, networking, delays)
  • Replacing coroutines with async/await
  • Managing cancellation in MonoBehaviours
  • Async initialization patterns
  • Parallel async operations

Installation

json
// manifest.json
"com.cysharp.unitask": "https://github.com/Cysharp/UniTask.git?path=src/UniTask/Assets/Plugins/UniTask"

Basic Patterns

Simple Async Method

csharp
public async UniTask LoadGameAsync()
{
    await UniTask.Delay(1000); // 1 second delay
    await LoadAssetsAsync();
    await InitializeSystemsAsync();
}

Async with Return Value

csharp
public async UniTask<PlayerData> LoadPlayerAsync()
{
    var json = await File.ReadAllTextAsync(path);
    return JsonUtility.FromJson<PlayerData>(json);
}

Fire-and-Forget (Use Carefully!)

csharp
// ForgetTask() suppresses warnings but loses error handling
LoadGameAsync().Forget();

// Better: Use UniTaskVoid for true fire-and-forget
public async UniTaskVoid StartBackgroundTask()
{
    try
    {
        await DoWorkAsync();
    }
    catch (Exception ex)
    {
        Debug.LogException(ex);
    }
}

Cancellation Patterns

Basic CancellationToken

csharp
public class GameLoader : MonoBehaviour
{
    private CancellationTokenSource _cts;
    
    private void OnEnable()
    {
        _cts = new CancellationTokenSource();
        LoadAsync(_cts.Token).Forget();
    }
    
    private void OnDisable()
    {
        _cts?.Cancel();
        _cts?.Dispose();
        _cts = null;
    }
    
    private async UniTask LoadAsync(CancellationToken ct)
    {
        await UniTask.Delay(1000, cancellationToken: ct);
        // Work here...
    }
}

Destroy CancellationToken (Preferred for MonoBehaviour)

csharp
public class Enemy : MonoBehaviour
{
    private async UniTaskVoid Start()
    {
        // Automatically cancelled when GameObject destroyed
        var ct = this.GetCancellationTokenOnDestroy();
        
        while (!ct.IsCancellationRequested)
        {
            await UniTask.Delay(1000, cancellationToken: ct);
            Patrol();
        }
    }
}

Linked Cancellation

csharp
public async UniTask DoWorkAsync(CancellationToken externalCt)
{
    // Link external token with destroy token
    var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(
        externalCt,
        this.GetCancellationTokenOnDestroy()
    );
    
    try
    {
        await LongRunningTask(linkedCts.Token);
    }
    finally
    {
        linkedCts.Dispose();
    }
}

Timeout

csharp
// Timeout with exception
await task.Timeout(TimeSpan.FromSeconds(5));

// Timeout without exception
var (hasValue, result) = await task.TimeoutWithoutException(TimeSpan.FromSeconds(5));
if (!hasValue)
{
    Debug.Log("Operation timed out");
}

// Timeout with CancellationTokenSource
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
await task.AttachExternalCancellation(cts.Token);

Unity Lifecycle Integration

Waiting for Frames

csharp
// Wait one frame
await UniTask.Yield();

// Wait for end of frame
await UniTask.WaitForEndOfFrame();

// Wait for fixed update
await UniTask.WaitForFixedUpdate();

// Wait multiple frames
await UniTask.DelayFrame(10);

// Wait for specific player loop
await UniTask.Yield(PlayerLoopTiming.PreUpdate);

Player Loop Timing Options

csharp
// Available timings:
PlayerLoopTiming.Initialization
PlayerLoopTiming.EarlyUpdate
PlayerLoopTiming.FixedUpdate
PlayerLoopTiming.PreUpdate
PlayerLoopTiming.Update
PlayerLoopTiming.PreLateUpdate
PlayerLoopTiming.PostLateUpdate
PlayerLoopTiming.TimeUpdate

Waiting for Conditions

csharp
// Wait until condition is true
await UniTask.WaitUntil(() => player.IsReady);

// Wait while condition is true
await UniTask.WaitWhile(() => isLoading);

// Wait until with cancellation
await UniTask.WaitUntil(
    () => player.IsReady,
    cancellationToken: ct
);

// Wait until with timeout
await UniTask.WaitUntil(() => player.IsReady)
    .Timeout(TimeSpan.FromSeconds(10));

Waiting for Unity Events

csharp
// Wait for button click
await button.OnClickAsync();

// Wait for trigger enter
var other = await gameObject.OnTriggerEnterAsync();

// Wait for collision
var collision = await gameObject.OnCollisionEnterAsync();

// Wait for animation event
await animator.WaitForAnimationEvent("AttackHit");

Parallel Operations

WhenAll (Wait for All)

csharp
// Wait for all tasks to complete
var results = await UniTask.WhenAll(
    LoadTexturesAsync(),
    LoadAudioAsync(),
    LoadConfigAsync()
);

// With different return types
var (textures, audio, config) = await UniTask.WhenAll(
    LoadTexturesAsync(),
    LoadAudioAsync(),
    LoadConfigAsync()
);

WhenAny (Wait for First)

csharp
// Wait for first to complete
var (winIndex, result1, result2) = await UniTask.WhenAny(
    TryServerAAsync(),
    TryServerBAsync()
);

// Use winner
if (winIndex == 0)
{
    UseResult(result1);
}

Throttling Parallel Operations

csharp
// Process with limited concurrency
var semaphore = new SemaphoreSlim(3); // Max 3 concurrent

await UniTask.WhenAll(items.Select(async item =>
{
    await semaphore.WaitAsync();
    try
    {
        await ProcessItemAsync(item);
    }
    finally
    {
        semaphore.Release();
    }
}));

Coroutine Interop

Convert Coroutine to UniTask

csharp
// Wrap existing coroutine
await MyCoroutine().ToUniTask();

// With cancellation
await MyCoroutine().ToUniTask(cancellationToken: ct);

// From IEnumerator
IEnumerator LegacyCoroutine()
{
    yield return new WaitForSeconds(1);
}

await LegacyCoroutine().ToUniTask();

Convert UniTask to Coroutine

csharp
// For APIs that require coroutines
StartCoroutine(MyUniTask().ToCoroutine());

Async Trigger Components

csharp
// Add async triggers to GameObjects
var trigger = gameObject.GetAsyncTriggerEnterTrigger();

// Wait for trigger
var other = await trigger.OnTriggerEnterAsync();

Resource Loading

Addressables Integration

csharp
public async UniTask<T> LoadAssetAsync<T>(string address, CancellationToken ct)
{
    var handle = Addressables.LoadAssetAsync<T>(address);
    
    try
    {
        return await handle.ToUniTask(cancellationToken: ct);
    }
    catch (OperationCanceledException)
    {
        Addressables.Release(handle);
        throw;
    }
}

Scene Loading

csharp
public async UniTask LoadSceneAsync(string sceneName, CancellationToken ct)
{
    await SceneManager.LoadSceneAsync(sceneName)
        .ToUniTask(cancellationToken: ct);
}

// With progress
public async UniTask LoadSceneWithProgressAsync(string sceneName, IProgress<float> progress)
{
    await SceneManager.LoadSceneAsync(sceneName)
        .ToUniTask(progress: progress);
}

Asset Bundle Loading

csharp
public async UniTask<AssetBundle> LoadBundleAsync(string url, CancellationToken ct)
{
    var request = UnityWebRequestAssetBundle.GetAssetBundle(url);
    
    await request.SendWebRequest().ToUniTask(cancellationToken: ct);
    
    if (request.result != UnityWebRequest.Result.Success)
    {
        throw new Exception(request.error);
    }
    
    return DownloadHandlerAssetBundle.GetContent(request);
}

Error Handling

Try-Catch Pattern

csharp
public async UniTask SafeLoadAsync()
{
    try
    {
        await LoadDataAsync();
    }
    catch (OperationCanceledException)
    {
        // Expected when cancelled - don't log as error
        Debug.Log("Load cancelled");
    }
    catch (Exception ex)
    {
        Debug.LogException(ex);
        ShowErrorUI();
    }
}

SuppressCancellationThrow

csharp
// Returns (isCancelled, result) instead of throwing
var (cancelled, result) = await LoadAsync()
    .SuppressCancellationThrow();

if (cancelled)
{
    return; // Graceful exit
}

ProcessResult(result);

Exception Handling in WhenAll

csharp
// Collect all exceptions
try
{
    await UniTask.WhenAll(tasks);
}
catch (AggregateException ae)
{
    foreach (var ex in ae.InnerExceptions)
    {
        Debug.LogException(ex);
    }
}

Progress Reporting

IProgress

csharp
public async UniTask LoadWithProgressAsync(IProgress<float> progress, CancellationToken ct)
{
    var items = await GetItemsAsync();
    
    for (int i = 0; i < items.Count; i++)
    {
        await ProcessItemAsync(items[i], ct);
        progress?.Report((float)(i + 1) / items.Count);
    }
}

// Usage
var progress = new Progress<float>(p => loadingBar.value = p);
await LoadWithProgressAsync(progress, ct);

Custom Progress

csharp
public struct LoadProgress
{
    public string CurrentItem;
    public int Loaded;
    public int Total;
    public float Percent => (float)Loaded / Total;
}

public async UniTask LoadAsync(IProgress<LoadProgress> progress)
{
    var items = await GetItemsAsync();
    
    for (int i = 0; i < items.Count; i++)
    {
        progress?.Report(new LoadProgress
        {
            CurrentItem = items[i].Name,
            Loaded = i + 1,
            Total = items.Count
        });
        
        await ProcessItemAsync(items[i]);
    }
}

UniTask vs Task

When to Use UniTask

csharp
// Unity main thread operations
await UniTask.Delay(1000);              // Use UniTask
await UniTask.Yield();                   // Use UniTask
await SceneManager.LoadSceneAsync(s);    // Use UniTask

// Fire and forget in Unity
DoWorkAsync().Forget();                  // UniTask only

When to Use Task

csharp
// Pure .NET operations (no Unity API)
await File.ReadAllTextAsync(path);       // Task is fine
await Task.Run(() => HeavyComputation()); // Task for thread pool

// Converting
var result = await task.AsUniTask();     // Task to UniTask
var task = unitask.AsTask();             // UniTask to Task

Common Pitfalls

Pitfall 1: Missing CancellationToken

csharp
// BAD: No cancellation, leaks when object destroyed
public async UniTaskVoid Start()
{
    await UniTask.Delay(10000);
    DoSomething(); // May crash if destroyed
}

// GOOD: Use destroy token
public async UniTaskVoid Start()
{
    await UniTask.Delay(10000, cancellationToken: destroyCancellationToken);
    DoSomething();
}

Pitfall 2: Forget Without Error Handling

csharp
// BAD: Exceptions silently swallowed
DoWorkAsync().Forget();

// GOOD: Handle errors
async UniTaskVoid DoWorkSafe()
{
    try
    {
        await DoWorkAsync();
    }
    catch (Exception ex) when (!(ex is OperationCanceledException))
    {
        Debug.LogException(ex);
    }
}
DoWorkSafe().Forget();

Pitfall 3: Blocking on Main Thread

csharp
// BAD: Blocks main thread
var result = LoadAsync().GetAwaiter().GetResult();

// GOOD: Await properly
var result = await LoadAsync();

Pitfall 4: Unnecessary Allocations

csharp
// BAD: Allocates closure
await UniTask.Delay(1000).ContinueWith(_ => DoSomething());

// GOOD: Just await
await UniTask.Delay(1000);
DoSomething();

Best Practices

  1. Always use CancellationToken for MonoBehaviour async methods
  2. Use GetCancellationTokenOnDestroy() for automatic cleanup
  3. Handle OperationCanceledException separately from other exceptions
  4. Prefer UniTask over Task for Unity operations
  5. Use WhenAll for parallel operations
  6. Report progress for long-running operations
  7. Use SuppressCancellationThrow for optional cancellation handling
  8. Avoid Forget() without proper error handling

Performance Tips

  • UniTask is struct-based (zero allocation when awaited directly)
  • Avoid unnecessary .AsTask() conversions
  • Use UniTask.Yield() instead of await UniTask.Delay(0)
  • Pool CancellationTokenSource for high-frequency operations
  • Use UniTaskCompletionSource for custom async patterns

Heefeg gestallte Froen

Wat mécht de KI-Skill Tools Unity Unitask?

UniTask async/await patterns for Unity including cancellation, lifecycle binding, and coroutine interop.

Firwat Tools Unity Unitask op TypingMind benotzen?

Well Dir en eemol installéiert a mat all Modell benotze kënnt. Tools Unity Unitask besteet aus einfachem Markdown amplaz vun ubidderspezifeschem Code. Dee selwechte Skill funktionéiert also mat GPT-5, Claude, Gemini, Grok oder engem lokale Modell – an Dir kënnt de Modell matzen am Chat wiesselen, ouni datt de Skill ophält ze funktionéieren. TypingMind benotzt Är eegen API-Schlësselen, sou datt Dir d'Ubidder direkt bezuelt amplaz vun engem Abonnement pro Benotzerplaz. Är Skills a Chats bleiwen an Ärem eegene Späicher.

Wéi installéieren ech Tools Unity Unitask an TypingMind?

Maacht an TypingMind Plugins → Skills → Vu GitHub installéieren op a setzt https://github.com/IdoCohen560/claude-unity-game-studio/tree/main/examples/my-first-game/.claude/skills/tools-unity-unitask an. TypingMind liest d'Datei SKILL.md an installéiert de Skill, deen Dir pro Chat aktivéiere kënnt.

Wéi eng KI-Modeller kënnen Tools Unity Unitask benotzen?

All Modell, deen Dir an TypingMind verbënnt. KI-Skills sinn einfach Markdown-Instruktiounen an net ubidderspezifesche Code. Dofir kënne GPT, Claude, Gemini, Grok a lokal Modeller dëse Skill lueden, wann eng Ufro dozou passt.

Wéi vill KI-Modeller kann ech mat Tools Unity Unitask benotzen?

Esou vill Dir wëllt. Soulaang e Modell Skills ënnerstëtzt, kënnt Dir Tools Unity Unitask domat benotzen – GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama a méi – alles op TypingMind mat Ären eegenen API-Schlësselen.

Ass de KI-Skill Tools Unity Unitask gratis?

Jo. De Skill gëtt vum IdoCohen560 ënner der Lizenz MIT op GitHub publizéiert. Dir bezuelt nëmmen Ären eegene KI-Ubidder fir d'Token, déi Dir benotzt.

Wat si KI-Skills?

E KI-Skill ass e weiderverwendbaart Pak vun Instruktiounen, dat engem KI-Modell bäibréngt, wéi en eng bestëmmt Aufgab erfëllt. E follegt dem oppenen Agent Skills-Format: eng Datei SKILL.md mat engem Numm an enger Beschreiwung, plus all Scripten, Virlagen oder Referenzdateien, déi de Modell eventuell brauch. De Modell liest d'Instruktiounen eréischt, wann Är Ufro zum Skill passt. En installéierte Skill kascht also näischt, bis e benotzt gëtt.

Wéi ënnerscheede sech KI-Skills vu Plugins oder MCP-Serveren?

E Plugin oder MCP-Server gëtt engem Modell nei Tools, déi en opruffe kann – Code, deen iergendwou leeft an e Resultat zeréckgëtt. E KI-Skill gëtt dem Modell dogéint Wëssen an eng Virgoensweis: wéi en eng Aufgab ugeet, wéi eng Schrëtt en nokënnt a wéi eng gutt Ausgab ausgesäit. Skills bestinn aus einfachem Markdown, brauche kee Server, keen API-Schlëssel a keng Lafzäitëmfeld a funktionéiere mat all Modell.

All weisen

Elo Ären eegene KI-Workspace ariichten

Abonnéiert Iech op eisen Newsletter, fir iwwer nei Funktiounen an zukünfteg Gewënnspiller informéiert ze ginn 👇