コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【Unity】InvalidOperationException: Token version is not matched, can not await twice or get Status after await.

概要

using Cysharp.Threading.Tasks;
using UnityEngine;

public class Example : MonoBehaviour
{
    private async UniTask Start()
    {
        var task = UniTask.NextFrame();

        await task;
        await task;
    }
}

1 つの UniTask のインスタンスを 2 回以上 await すると

InvalidOperationException: Token version is not matched, can not await twice or get Status after await.

上記の例外が発生する

using Cysharp.Threading.Tasks;
using UnityEngine;

public class Example : MonoBehaviour
{
    private async UniTask Start()
    {
        var task = UniTask.NextFrame().Preserve();

        await task;
        await task;
    }
}

2 回以上 await したい場合は Preserve を呼んでおく