loading sprite from atlas in script

there are questions already on this, but as far as i can see none of them have an answer that works…

how can a sprite packed in an atlas (packed by giving a packing tag to the sprites) be loaded in code?

we can’t use Resources.Load, because the sprites can’t be in a resources folder (they won’t pack into an atlas if they’re in a resources folder).

we can’t use AssetDatabase, because it only works when running in the editor.

the idea is to avoid prefabs, and load the sprite directly, because i need to do a lot of stuff dynamically, and also don’t want to have to create prefabs for hundreds of sprites.

any way to do this?

Maybe you’re looking for something like this?

public Dictionary<string, Sprite> dictSprites = new Dictionary<string, Sprite>();
 
     void Start()
     {
          Sprite[] sprites = Resources.LoadAll<Sprite>("SpriteSheet");
         
          foreach (Sprite sprite in sprites)
          {
               dictSprites.Add(sprite.name, sprite)
          }
     }
     GetComponent<SpriteRenderer>().sprite = dictSprites[name];

You could obviously also leave it in just an array and access through indices, although if there are 10+ sprites per sheet counting an index can get irritating.

Hope this helps,

Bentley

Rather than making prefabs, you can make a game object with a public list of sprites… and then drag all your sprites into that list…

Then, on start… put all the sprites into a public dictionary by name and clear the list…

Then you can load them by name from the dictionary.

Without some convoluted method it isn’t possible but you can up vote it!!
http://feedback.unity3d.com/suggestions/allow-access-to-sprite-packer-atlas-to-retrieve-sprites-by-name

I wrote this code I have 42 png avatars But when i run new Game Object gets initialized 42 times
Please help!

public GameObject gridGameObject;
public Dictionary<string, Sprite> dictSprites;
void Awake()
{
dictSprites = new Dictionary<string, Sprite>();
}
// Use this for initialization
void Start () {
Sprite sprites = Resources.LoadAll(“Avatars”);

    foreach (Sprite sprite in sprites)
    {
        dictSprites.Add(sprite.name, sprite);
        NGUITools.AddChild(gridGameObject, sprite);
        
    }
}