Skip to content

Instantly share code, notes, and snippets.

@ksnnacar
Last active December 1, 2021 08:54
Show Gist options
  • Save ksnnacar/953a62b38d65fb4ee346c4be4776329e to your computer and use it in GitHub Desktop.
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.
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
}
@wisestump
Copy link

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:

if (s == null || atlas.CanBindTo(sprite) == false)
    continue;

@ksnnacar
Copy link
Author

ksnnacar commented Dec 1, 2021

@wisestump thanks for the suggestion, 👍 added

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment