1
2
3
4
5
6
7
8
9
public class AsyncExample : MonoBehaviour
{
async void Start()
{
Debug.Log("Waiting 1 second...");
await Task.Delay(TimeSpan.FromSeconds(1));
Debug.Log("Done!");
}
}
1
2
3
4
5
6
7
public static class AwaitExtensions
{
public static TaskAwaiter GetAwaiter(this TimeSpan timeSpan)
{
return Task.Delay(timeSpan).GetAwaiter();
}
}
1
2
3
4
5
6
7
public class AsyncExample : MonoBehaviour
{
async void Start()
{
await TimeSpan.FromSeconds(1);
}
}
public class AsyncExample : MonoBehaviour
{
public async void Start()
{
// Wait one second
await new WaitForSeconds(1.0f);
// Wait for IEnumerator to complete
await CustomCoroutineAsync();
await LoadModelAsync();
// You can also get the final yielded value from the coroutine
var value = (string)(await CustomCoroutineWithReturnValue());
// value is equal to "asdf" here
// Open notepad and wait for the user to exit
var returnCode = await Process.Start("notepad.exe");
// Load another scene and wait for it to finish loading
await SceneManager.LoadSceneAsync("scene2");
}
async Task LoadModelAsync()
{
var assetBundle = await GetAssetBundle("www.my-server.com/myfile");
var prefab = await assetBundle.LoadAssetAsync<GameObject>("myasset");
GameObject.Instantiate(prefab);
assetBundle.Unload(false);
}
async Task<AssetBundle> GetAssetBundle(string url)
{
return (await new WWW(url)).assetBundle
}
IEnumerator CustomCoroutineAsync()
{
yield return new WaitForSeconds(1.0f);
}
IEnumerator CustomCoroutineWithReturnValue()
{
yield return new WaitForSeconds(1.0f);
yield return "asdf";
}
}