「Unity/Addressable/複数ロード」の版間の差分
提供: 初心者エンジニアの簡易メモ
| 行15: | 行15: | ||
public class AssetLabelsLoadScene : MonoBehaviour | public class AssetLabelsLoadScene : MonoBehaviour | ||
{ | { | ||
| + | [SerializeField] | ||
| + | Button clearButton; | ||
[SerializeField] | [SerializeField] | ||
Button loadButton; | Button loadButton; | ||
| + | [SerializeField] | ||
| + | Button unloadButton; | ||
[SerializeField] | [SerializeField] | ||
GameObject canvas; | GameObject canvas; | ||
| − | GameObject | + | IList<GameObject> instances; |
| + | IList<GameObject> list; | ||
void Start() | void Start() | ||
{ | { | ||
| + | clearButton.onClick.AddListener(() => { | ||
| + | Caching.ClearCache(); | ||
| + | }); | ||
loadButton.onClick.AddListener(() => { | loadButton.onClick.AddListener(() => { | ||
| − | if ( | + | if (instances == null) |
{ | { | ||
| + | instances = new List<GameObject>(); | ||
StartCoroutine(Load()); | StartCoroutine(Load()); | ||
} | } | ||
| + | }); | ||
| + | unloadButton.onClick.AddListener(() => { | ||
| + | foreach (var instance in instances) | ||
| + | { | ||
| + | Destroy(instance); | ||
| + | Addressables.ReleaseInstance(instance); // 破棄 | ||
| + | } | ||
| + | instances = null; | ||
}); | }); | ||
} | } | ||
| − | |||
IEnumerator Load() | IEnumerator Load() | ||
{ | { | ||
| 行40: | 行56: | ||
{ | { | ||
Debug.Log(value.name); | Debug.Log(value.name); | ||
| + | var instance = Instantiate(value, canvas.transform); | ||
| + | instances.Add(instance); | ||
} | } | ||
} | } | ||
2022年10月10日 (月) 20:36時点における最新版
準備
複数まとめてロードするには、Labelsの機能を使う
- Unityメインメニュー/Window/Asset Management/Addressables/Groupsを選択
- ロードしたいオブジェクトのLabels部分にラベル名を追加(例:"TestLabel")
サンプル
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
using UnityEngine.UI;
public class AssetLabelsLoadScene : MonoBehaviour
{
[SerializeField]
Button clearButton;
[SerializeField]
Button loadButton;
[SerializeField]
Button unloadButton;
[SerializeField]
GameObject canvas;
IList<GameObject> instances;
IList<GameObject> list;
void Start()
{
clearButton.onClick.AddListener(() => {
Caching.ClearCache();
});
loadButton.onClick.AddListener(() => {
if (instances == null)
{
instances = new List<GameObject>();
StartCoroutine(Load());
}
});
unloadButton.onClick.AddListener(() => {
foreach (var instance in instances)
{
Destroy(instance);
Addressables.ReleaseInstance(instance); // 破棄
}
instances = null;
});
}
IEnumerator Load()
{
var handle = Addressables.LoadAssetsAsync<GameObject>("TestLabel", null);
yield return handle;
if (handle.Status == AsyncOperationStatus.Succeeded)
{
list = handle.Result;
foreach (var value in list)
{
Debug.Log(value.name);
var instance = Instantiate(value, canvas.transform);
instances.Add(instance);
}
}
}
}
実行に失敗する場合は、Addressablesを再ビルドしてるか確認する
