UniTask icon indicating copy to clipboard operation
UniTask copied to clipboard

Can't exit await when stopping Unity Editor

Open nyancodev opened this issue 1 year ago • 3 comments

Unity: 2022.3.21f1 UniTask: 2.5.4

If you stop the Unity Editor with this code, it will not advance to wait3 If you destroy GameObject, proceed to wait3 Is this behavior due to the fact that PlayerLoop must be stopped in the Unity Editor?

public class Sample : MonoBehaviour
{
    public async void OnDestroy()
    {
        await UniTask.WaitUntil(() => true);
        Debug.Log("wait1");
        await UniTask.WaitUntil(() => true);
        Debug.Log("wait2");
        await UniTask.WaitUntil(() => true);
        Debug.Log("wait3");
    }
}

nyancodev avatar May 30 '24 09:05 nyancodev

The problem here is that you're using async void, which uses System.Threading.Tasks.Task (instead of UniTask), and it uses the default SynchronizationContext (which doesn't care about enter/exit playmode at all).

I recommend changing the code to something like this instead ` private void OnDestroy() { // kick off async method OnDestroyAsync().Forget(); }

private async UniTaskVoid OnDestroyAsync() { // ... your async code here } `

Monsoonexe avatar Oct 10 '24 19:10 Monsoonexe

I tried the code I was presented, but it didn't work After all there is await that does not proceed when the editor is stopped

nyancodev avatar Oct 21 '24 06:10 nyancodev

Oh, you DO want the code to continue when leaving PlayMode? Don't use UniTask -- it specifically is designed to not do this. Use built-in Task instead.

Monsoonexe avatar Oct 21 '24 12:10 Monsoonexe

Use a built -in task

nyancodev avatar Dec 09 '24 09:12 nyancodev