Posted at

Addressable Assets Systemで AsObservable

More than 1 year has passed since last update.

前に似たような奴を描いたけど今回も同様の拡張

ただの変換だけど備忘録的に残しとく


AddressableAssetAsObservable.cs


public static class AddressableAssetAsObservable
{
public static IObservable<IAsyncOperation<TObject>> AsObservable<TObject>(this IAsyncOperation<TObject> addressableAsync)
{
return Observable.FromEvent<IAsyncOperation<TObject>>(
h => addressableAsync.Completed += h,
h => addressableAsync.Completed -= h);
}

}


こうすることで


DataLoader.cs


public class DataLoader
{
public async UniTask<SettingData> Load()
{
var textAsset = await Addressables.LoadAsset<TextAsset>("honyararaData")
.AsObservable()
.First();

var settingData = JsonUtility.FromJson<SettingData>(textAsset.Result.text);

return settingData;
}
}


とか書ける。


MogemogeGameObject.cs


public class csharp:MogemogeGameObject:MonoBehaviour
{
void Start()
{
Addressables.LoadAsset<Texture2D>("icon")
.AsObservable()
.Subscribe(texture => icon.material.SetTexture("_MainTex", texture))
.AddTo(this);
}
}


みたいに書き慣れた感じで書ける。