Skip to content

Instantly share code, notes, and snippets.

@yKimisaki
Last active March 18, 2021 00:48
Show Gist options
  • Save yKimisaki/5f7d2846ba21fd9bfb5358de6e5f0ed8 to your computer and use it in GitHub Desktop.
Save yKimisaki/5f7d2846ba21fd9bfb5358de6e5f0ed8 to your computer and use it in GitHub Desktop.
#if CSHARP_7_OR_LATER
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
using System;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement;
namespace UniRx.Async
{
public static class LazyUniTask
{
public static UniTask<T> Create<T>(Func<UniTask<T>> taskFactory) where T : class
{
return new UniTask<T>(taskFactory);
}
// Resources.LoadAsync
public static UniTask<T> LoadResources<T>(string path) where T : UnityEngine.Object
{
return new UniTask<T>(() =>
{
var completionSource = new UniTaskCompletionSource<T>();
var loadTask = Resources.LoadAsync<T>(path);
loadTask.completed += x => completionSource.TrySetResult(loadTask.asset as T);
return completionSource.Task;
});
}
// Addressable Assets System
public static UniTask<T> LoadAddressables<T>(IResourceLocation location) where T : class
{
return new UniTask<T>(() =>
{
var completionSource = new UniTaskCompletionSource<T>();
Addressables.LoadAsset<T>(location).Completed += x => completionSource.TrySetResult(x.Result);
return completionSource.Task;
});
}
// Addressable Assets System
public static UniTask<T> LoadAddressables<T>(object key) where T : class
{
return new UniTask<T>(() =>
{
var completionSource = new UniTaskCompletionSource<T>();
Addressables.LoadAsset<T>(key).Completed += x => completionSource.TrySetResult(x.Result);
return completionSource.Task;
});
}
}
}
#endif
@yKimisaki
Copy link
Author

class Character
{
    private AsyncLazy<Sprite> FaceIcon;
    
    public Character(int characterId)
    {
        this.FaceIcon = AsyncLazy.LoadResources<Sprite>(characterId + ".png");
    }
}

// ==

async Task InitializeAsync()
{
    image.sprite = await chara.FaceIcon;
}

@flycarl
Copy link

flycarl commented Aug 6, 2019

seem no need to surround return new UniTask<T>(() => { ... })

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment