unitask

repo

https://github.com/Cysharp/UniTask.git?path=src/UniTask/Assets/Plugins/UniTask

how to return a type

public async UniTask<Data> waitForData()
{
    await UniTask.WaitUntil(() => getData() != null);
    return getData();
}

Snippet to show how to handle cancellation

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

using System.Threading;
using Cysharp.Threading.Tasks;

public class UnitaskTest : MonoBehaviour
{
    CancellationTokenSource token;

    [ContextMenu("start")]
    void taskStart()
    {
        Debug.Log("start");
        token = new CancellationTokenSource();

        doWrapper().Forget();
    }

    async UniTaskVoid doWrapper()
    {
        Debug.Log("wrap:start");
        bool canceled = await doSomething().SuppressCancellationThrow();
        if(canceled)
        {
            Debug.Log("wrap:canceled");
        }
        Debug.Log("wrap:end");
    }

    async UniTask doSomething()
    {
        Debug.Log("do");

        await UniTask.WaitUntil(() =>
        {
            return Input.GetMouseButtonUp(0);
        }, cancellationToken:token.Token);

        Debug.Log("done");
    }

    [ContextMenu("interrupt")]
    void taskInterrupt()
    {
        Debug.Log("interrupt");

        token.Cancel();
    }
}