Created
December 18, 2019 20:19
-
-
Save jmschrack/9b92673dfcf4246dba129d65bce6bf4e to your computer and use it in GitHub Desktop.
Extensions that turns Unity's AsyncOperations into true C# async/await. Full credit to james7132 on the unity forum
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
From https://forum.unity.com/threads/will-unity-ever-make-a-move-to-async-await-task.557908/#post-3699391 | |
Full credit to james7132 | |
*/ | |
public static class IAsyncOperationExtensions { | |
public static AsyncOperationAwaiter GetAwaiter(this IAsyncOperation operation) { | |
return new AsyncOperationAwaiter(operation); | |
} | |
public static AsyncOperationAwaiter<T> GetAwaiter<T>(this IAsyncOperation<T> operation) where T : Object { | |
return new AsyncOperationAwaiter<T>(operation); | |
} | |
public readonly struct AsyncOperationAwaiter : INotifyCompletion { | |
readonly IAsyncOperation _operation; | |
public AsyncOperationAwaiter(IAsyncOperation operation) { | |
_operation = operation; | |
} | |
public bool IsCompleted => _operation.Status != AsyncOperationStatus.None; | |
public void OnCompleted(Action continuation) => _operation.Completed += (op) => continuation?.Invoke(); | |
public object GetResult() => _operation.Result; | |
} | |
public readonly struct AsyncOperationAwaiter<T> : INotifyCompletion where T : Object { | |
readonly IAsyncOperation<T> _operation; | |
public AsyncOperationAwaiter(IAsyncOperation<T> operation) { | |
_operation = operation; | |
} | |
public bool IsCompleted => _operation.Status != AsyncOperationStatus.None; | |
public void OnCompleted(Action continuation) => _operation.Completed += (op) => continuation?.Invoke(); | |
public T GetResult() => _operation.Result; | |
} | |
} | |
// This makes the following code compile without issue: | |
/* | |
async void TestAsyncAddressables() { | |
Sprite sprite = await assetReference.LoadAsset<Sprite>(); | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment