// [UNITY-SKILL:SPRITEATLAS] // [TYPE:RUNTIME-LOADER] // Generated by SpriteAtlas Skill // This script handles late-binding atlas loading via Addressables using UnityEngine; using UnityEngine.U2D; using System.Collections.Generic; #if UNITY_ADDRESSABLES using UnityEngine.AddressableAssets; using UnityEngine.ResourceManagement.AsyncOperations; #endif /// /// Late-binding loader for SpriteAtlas via Addressables /// Automatically loads atlases on-demand when sprites are requested /// public class SpriteAtlasLateBinding : MonoBehaviour { private static SpriteAtlasLateBinding instance; #if UNITY_ADDRESSABLES private Dictionary> loadedAtlases = new Dictionary>(); #endif void Awake() { if (instance != null && instance != this) { Destroy(gameObject); return; } instance = this; DontDestroyOnLoad(gameObject); // Register late-binding callback SpriteAtlasManager.atlasRequested += OnAtlasRequested; SpriteAtlasManager.atlasRegistered += OnAtlasRegistered; } void OnDestroy() { SpriteAtlasManager.atlasRequested -= OnAtlasRequested; SpriteAtlasManager.atlasRegistered -= OnAtlasRegistered; #if UNITY_ADDRESSABLES // Release all loaded atlases foreach (var handle in loadedAtlases.Values) { if (handle.IsValid()) { Addressables.Release(handle); } } loadedAtlases.Clear(); #endif } private void OnAtlasRequested(string tag, System.Action callback) { #if UNITY_ADDRESSABLES // Check if already loaded if (loadedAtlases.ContainsKey(tag)) { var handle = loadedAtlases[tag]; if (handle.IsDone && handle.Status == AsyncOperationStatus.Succeeded) { callback(handle.Result); return; } } // Load atlas asynchronously Debug.Log($"[SpriteAtlas] Loading atlas via Addressables: {tag}"); var loadHandle = Addressables.LoadAssetAsync(tag); loadedAtlases[tag] = loadHandle; loadHandle.Completed += (handle) => { if (handle.Status == AsyncOperationStatus.Succeeded) { Debug.Log($"[SpriteAtlas] Successfully loaded atlas: {tag} with {handle.Result.spriteCount} sprites"); callback(handle.Result); } else { Debug.LogError($"[SpriteAtlas] Failed to load atlas: {tag}"); } }; #else Debug.LogError($"[SpriteAtlas] Addressables package not installed. Cannot load atlas: {tag}"); callback(null); #endif } private void OnAtlasRegistered(SpriteAtlas atlas) { Debug.Log($"[SpriteAtlas] Atlas registered: {atlas.name}"); } /// /// Manually preload an atlas (optional) /// public static void PreloadAtlas(string atlasName) { #if UNITY_ADDRESSABLES if (instance == null) { Debug.LogError("[SpriteAtlas] SpriteAtlasLateBinding instance not found. Add to scene."); return; } if (!instance.loadedAtlases.ContainsKey(atlasName)) { var handle = Addressables.LoadAssetAsync(atlasName); instance.loadedAtlases[atlasName] = handle; Debug.Log($"[SpriteAtlas] Preloading atlas: {atlasName}"); } #endif } }