Hello, i have atlas (many sprites have one packing tag), how i can get list of all sprites, or get one sprite by name?
I don’t believe that only way is Load from resources (Resources.Load)
You can’t access the sprites directly from a Texture2d set up as a sprite atlas.
You can however access them from the texture’s asset. The texture is the main asset and all sprites are sub assets.
This should work:
Let me know if there are any errors.
void doSomethingWithAtlasSprites(Texture2D atlas)
{
String atlasPath;
Object[] atlasAssets;
atlasPath = AssetDatabase.GetAssetPath(atlas);
atlasAssets = AssetDatabase.LoadAllAssetsAtPath(atlasPath);
foreach(Object asset in atlasAssets)
{
if(AssetDatabase.IsSubAsset(asset))
{
//asset is a sprite.....
//do something
//add it to a list maybe
}
}
}
It is a part of my working code. Hope it helps.
public Texture2D spritesheetTexture = null;
private Sprite[] spritesArray = null;
//===============================================================================
private void LoadSpritesFromSpritesheet ()
{
if (this.spritesheetTexture == null) return;
if (this.spritesArray != null) this.spritesArray = null;
UnityEngine.Object[] spritesAsObjects = AssetDatabase.LoadAllAssetRepresentationsAtPath (AssetDatabase.GetAssetPath (this.spritesheetTexture));
if (spritesAsObjects == null) return;
this.spritesArray = new Sprite[spritesAsObjects.Length];
for (int i = 0; i < spritesAsObjects.Length; i++)
{
this.spritesArray _= spritesAsObjects *as Sprite;*_
}
}
//===============================================================================
* public Sprite GetSpriteByName (string spriteName, Sprite[] spriteArray)*
{
for (int i = 0; i < spriteArray.Length; i++)
{
if (spriteArray*.name.Equals (spriteName))*
{
return spriteArray*;*
}
}
return null;
}
I’m also looking for a way to get the material from a Sprite reference but the best I’ve been able to come up with right now is to have a SpriteRenderer from that packing tag present in your scene and then getting the sharedMaterial from that SpriteRenderer at runtime.
Use Unity’s built in Sprite Packer, how to load atlas?