facebook twitter hatena line email

Unity/Addressable/画像ロード

提供: 初心者エンジニアの簡易メモ
2022年10月11日 (火) 14:27時点におけるAdmin (トーク | 投稿記録)による版 (サンプル)

移動: 案内検索

手順

  1. Assets/Sprites/Icon.pngを用意
  2. 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;
    Sprite instance;
    void Start()
    {
        clearButton.onClick.AddListener(() => {
            Caching.ClearCache();
        });
        loadButton.onClick.AddListener(() => {
            if (instance == null)
            {
                StartCoroutine(Load());
            }
        });
        unloadButton.onClick.AddListener(() => {
            Destroy(instance);
            // Addressables.Release(instance); // 破棄
        });
    }
    IEnumerator Load()
    {
        var handle = Addressables.LoadAssetAsync<Sprite>("Assets/Sprites/Icon.png");
        yield return handle;
        if (handle.Status == AsyncOperationStatus.Succeeded)
        {
            instance = Instantiate(handle.Result, canvas.transform);
            image.sprite = instance;
        }
    }
}

参考:https://original-game.com/unity-how-to-use-addressables/