Last active
December 1, 2021 08:54
-
-
Save ksnnacar/953a62b38d65fb4ee346c4be4776329e to your computer and use it in GitHub Desktop.
Unity find atlas of a UI.Image.Sprite and set it as AssetReferenceAtlasedSprite.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Generic; | |
using UnityEngine; | |
using UnityEngine.AddressableAssets; | |
using UnityEngine.ResourceManagement.AsyncOperations; | |
using UnityEngine.U2D; | |
using UnityEngine.UI; | |
public class LoadAddressablesSprite : MonoBehaviour | |
{ | |
[SerializeField] private AssetReferenceAtlasedSprite assetReferenceSprite; | |
private Image m_image; | |
#if UNITY_EDITOR | |
[ContextMenu("Find Reference")] | |
public void FindReference() | |
{ | |
m_image = GetComponent<Image>(); | |
if (m_image.sprite != null) | |
{ | |
var sprite = m_image.sprite; | |
var atlasEntries = new List<UnityEditor.AddressableAssets.Settings.AddressableAssetEntry>(); | |
UnityEditor.AddressableAssets.AddressableAssetSettingsDefaultObject.Settings.GetAllAssets(atlasEntries, | |
false, null, | |
e => UnityEditor.AssetDatabase.GetMainAssetTypeAtPath(e.AssetPath) == | |
typeof(UnityEngine.U2D.SpriteAtlas)); | |
var spriteName = sprite.name; | |
if (spriteName.EndsWith("(Clone)")) | |
spriteName = spriteName.Replace("(Clone)", ""); | |
foreach (var a in atlasEntries) | |
{ | |
var atlas = UnityEditor.AssetDatabase.LoadAssetAtPath<SpriteAtlas>(a.AssetPath); | |
if (atlas == null) | |
continue; | |
var s = atlas.GetSprite(spriteName); | |
if (s == null || atlas.CanBindTo(sprite) == false) | |
continue; | |
if (UnityEditor.AssetDatabase.TryGetGUIDAndLocalFileIdentifier(atlas, out string guid, | |
out long localID)) | |
{ | |
assetReferenceSprite = new AssetReferenceAtlasedSprite(guid); | |
assetReferenceSprite.SetEditorSubObject(sprite); | |
} | |
break; | |
} | |
} | |
} | |
#endif | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I would suggest adding a check at line 40 for a case when different sprites with the same name belong to different atlases.
Like that: