using System.Collections; using UnityEngine; using UnityEngine.ResourceManagement.AsyncOperations; using UnityEngine.U2D; using UnityEngine.UI; public class ExtendImage : MonoBehaviour { [SerializeField] Image m_image; string recentLoadedSpriteName; Sprite recentLoadedSprite; string recentLoadedAtlasPath; string recentLoadedTexInAtlasName; SpriteAtlas recentLoadedAtlas; public RectTransform rectTransform => transform as RectTransform; public Image ImageComponent => m_image; private void Awake() { if(m_image is null) m_image = GetComponent(); } private void OnDestroy() { if(recentLoadedSprite != null) AddressableMgr.ReleaseAsset(recentLoadedSprite); if(recentLoadedAtlasPath != null) AddressableMgr.ReleaseAsset(recentLoadedAtlas); } public void SetImageAsync(string path) { CoroutineHandler.Instance.StartCoroutine(LoadImageAsync(path)); } IEnumerator LoadImageAsync(string path) { if (recentLoadedSpriteName == path) yield break; if (recentLoadedSprite != null) { AddressableMgr.ReleaseAsset(recentLoadedSprite); recentLoadedSprite = null; } recentLoadedSpriteName = path; if (!AddressableMgr.LoadAssetAsync(path, out AsyncOperationHandle handler)) yield break; yield return handler; if (handler.Status != AsyncOperationStatus.Succeeded) yield break; if (recentLoadedSpriteName == path) { ImageComponent.sprite = handler.Result; recentLoadedSprite = handler.Result; } else { AddressableMgr.ReleaseAsset(handler.Result); } } public void ReleaseAsyncImage() { if(recentLoadedSprite != null) { AddressableMgr.ReleaseAsset(recentLoadedSprite); ImageComponent.sprite = null; recentLoadedSpriteName = null; recentLoadedSprite = null; } } public void SetImageInAtlasAsync(string atlasPath, string imgName) { CoroutineHandler.Instance.StartCoroutine(LoadImageInAtlasAsync(atlasPath, imgName)); } IEnumerator LoadImageInAtlasAsync(string atlasPath, string imgName) { if (recentLoadedAtlasPath == atlasPath) { if(recentLoadedTexInAtlasName != imgName) { ImageComponent.sprite = recentLoadedAtlas.GetSprite(imgName); recentLoadedTexInAtlasName = imgName; } yield break; } if (recentLoadedAtlas != null) { AddressableMgr.ReleaseAsset(recentLoadedAtlas); recentLoadedAtlas = null; } recentLoadedAtlasPath = atlasPath; recentLoadedTexInAtlasName = imgName; if (!AddressableMgr.LoadAssetAsync(atlasPath, out AsyncOperationHandle handler)) yield break; yield return handler; if (handler.Status != AsyncOperationStatus.Succeeded) yield break; if (recentLoadedAtlasPath == atlasPath && recentLoadedTexInAtlasName == imgName) { ImageComponent.sprite = handler.Result.GetSprite(imgName); recentLoadedAtlas = handler.Result; } else { AddressableMgr.ReleaseAsset(handler.Result); } } public void ReleaseAsyncAtlasImage() { if(recentLoadedAtlas != null) { AddressableMgr.ReleaseAsset(recentLoadedAtlas); ImageComponent.sprite = null; recentLoadedAtlasPath = null; recentLoadedTexInAtlasName = null; recentLoadedAtlas = null; } } private void OnValidate() { if (m_image == null) m_image = GetComponent(); } }