今回はAddressablesにしたSprite (Images)をリストにしてみます。
Google先生への聞き方が悪かったのか思ったようにできなかったのでChat GPT先生にお願いしました。
Scriptable Objectを使う方法でうまくいったのでとりあえずこれで行きますが、ちょっと迂遠な気がしています。利用方法としては一つのImage GameObjectにクリックで次々に違う画像を表示するというものです。
Step 1: Scriptable Objectを作る
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "SpriteListContainer", menuName = "Custom/Sprite List Container")]
public class SpriteListContainer : ScriptableObject
{
public List spriteList = new List();
}
※ usingでSystem.Collections.Genericを入れないとだめ。
Step 2: AddressablesにSpriteを同じグループに登録
Step 3: Sprite Loaderを作る
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
using System.Collections.Generic;
public class SpriteLoader : MonoBehaviour
{
public SpriteListContainer spriteListContainerPrefab; // Reference to the ScriptableObject asset in the project
private SpriteListContainer spriteListContainerInstance; // Instance of the ScriptableObject
private void Start()
{
// Create an instance of the ScriptableObject
spriteListContainerInstance = Instantiate(spriteListContainerPrefab);
LoadSprites();
}
private void LoadSprites()
{
Addressables.LoadAssetsAsync("YourSpriteGroupKey", null).Completed += OnSpritesLoaded;
}
private void OnSpritesLoaded(AsyncOperationHandle<IList> handle)
{
if (handle.Status == AsyncOperationStatus.Succeeded)
{
// Update the ScriptableObject instance with the loaded sprites
spriteListContainerInstance.spriteList.Clear();
spriteListContainerInstance.spriteList.AddRange(handle.Result);
}
else
{
Debug.LogError($"Failed to load sprites: {handle.OperationException}");
}
}
}
これは別スクリプトにしてもいいのですが、私は既にあるスクリプトの中に入れ込んでしまいました。
Step 4: Scriptable Objetを作って上記にアタッチ
上記(Step 3)を含むcsファイルをGameObjectにアタッチします。
適当なフォルダに移動してCreate > Custom > Sprite List ContainerでScriptable Objectを作って、上記のスクリプトにInspectorからアタッチします。
Step 5: 最後にできたリストを使ってあげます
using UnityEngine;
public class SpriteUser : MonoBehaviour
{
public SpriteListContainer spriteListContainer;
private void Start()
{
// Access the list of sprites
List sprites = spriteListContainer.spriteList;
// Use the sprites as needed
foreach (Sprite sprite in sprites)
{
// Do something with each sprite
}
}
}
私の場合はStep 3とStep 5を一緒にしちゃいました。
最初に言ったように、イマイチこれがベストか分かりませんが、一つのやり方ということで。リリースしてないけど、いいのかな?