Advertisement
waygeek

SpriteManager

Jan 23rd, 2024 (edited)
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.40 KB | None | 0 0
  1. using UnityEngine;
  2. using UnityEngine.AddressableAssets;
  3. using UnityEngine.ResourceManagement.AsyncOperations;
  4. using System.Collections.Generic;
  5.  
  6. [CreateAssetMenu(fileName = "SpriteAsset", menuName = "Assets/SpriteAsset")]
  7. public class SpriteAsset : ScriptableObject
  8. {
  9.     public AssetReferenceSprite[] spriteReferences;
  10. }
  11.  
  12. public class SpriteManager : MonoBehaviour
  13. {
  14.     public SpriteAsset spriteAsset;
  15.     private Dictionary<string, Sprite> spriteDictionary;
  16.  
  17.     void Start()
  18.     {
  19.         InitializeSpriteDictionary();
  20.     }
  21.  
  22.     private void InitializeSpriteDictionary()
  23.     {
  24.         spriteDictionary = new Dictionary<string, Sprite>();
  25.  
  26.         foreach (AssetReferenceSprite spriteRef in spriteAsset.spriteReferences)
  27.         {
  28.             spriteRef.LoadAssetAsync<Sprite>().Completed += handle =>
  29.             {
  30.                 if (handle.Status == AsyncOperationStatus.Succeeded)
  31.                 {
  32.                     Sprite loadedSprite = handle.Result;
  33.                     spriteDictionary.Add(loadedSprite.name, loadedSprite);
  34.                 }
  35.             };
  36.         }
  37.     }
  38.  
  39.     public Sprite GetSprite(string id)
  40.     {
  41.         if (spriteDictionary.TryGetValue(id, out Sprite sprite))
  42.         {
  43.             return sprite;
  44.         }
  45.         else
  46.         {
  47.             Debug.LogWarning("Sprite with id " + id + " not found.");
  48.             return null;
  49.         }
  50.     }
  51. }
  52.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement