「Unity/Addressable/画像ロード」の版間の差分
提供: 初心者エンジニアの簡易メモ
(同じ利用者による、間の3版が非表示) | |||
行23: | 行23: | ||
[SerializeField] | [SerializeField] | ||
Image image; | Image image; | ||
− | Sprite | + | AsyncOperationHandle<Sprite> spriteHandle; |
void Start() | void Start() | ||
{ | { | ||
行30: | 行30: | ||
}); | }); | ||
loadButton.onClick.AddListener(() => { | loadButton.onClick.AddListener(() => { | ||
− | |||
− | |||
StartCoroutine(Load()); | StartCoroutine(Load()); | ||
− | |||
}); | }); | ||
unloadButton.onClick.AddListener(() => { | unloadButton.onClick.AddListener(() => { | ||
− | + | Addressables.Release(spriteHandle); // 破棄 | |
− | + | ||
}); | }); | ||
} | } | ||
行46: | 行42: | ||
if (handle.Status == AsyncOperationStatus.Succeeded) | if (handle.Status == AsyncOperationStatus.Succeeded) | ||
{ | { | ||
− | + | spriteHandle = handle; | |
− | image.sprite = | + | image.sprite = handle.Result; |
} | } | ||
} | } | ||
} | } | ||
</pre> | </pre> | ||
+ | |||
+ | 参考:https://note.com/hikohiro/n/n6cef6cc792a3 | ||
+ | |||
+ | 参考:https://original-game.com/unity-how-to-use-addressables/ |
2022年10月11日 (火) 14:49時点における最新版
手順
- Assets/Sprites/Icon.pngを用意
- Icon.pngのInspectorを開いてAddressableにチェックをいれ、Addressableのパスを"Assets/Sprites/Icon.png"で設定
サンプル
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AddressableAssets; using UnityEngine.ResourceManagement.AsyncOperations; using UnityEngine.UI; public class SpriteLoadScene : MonoBehaviour { [SerializeField] Button clearButton; [SerializeField] Button loadButton; [SerializeField] Button unloadButton; [SerializeField] GameObject canvas; [SerializeField] Image image; AsyncOperationHandle<Sprite> spriteHandle; void Start() { clearButton.onClick.AddListener(() => { Caching.ClearCache(); }); loadButton.onClick.AddListener(() => { StartCoroutine(Load()); }); unloadButton.onClick.AddListener(() => { Addressables.Release(spriteHandle); // 破棄 }); } IEnumerator Load() { var handle = Addressables.LoadAssetAsync<Sprite>("Assets/Sprites/Icon.png"); yield return handle; if (handle.Status == AsyncOperationStatus.Succeeded) { spriteHandle = handle; image.sprite = handle.Result; } } }