6
\$\begingroup\$

I have a spritesheet set up with the individual sprite regions named in unity. I haven't been able to find out how to access these sprites by name?

\$\endgroup\$

1 Answer 1

6
\$\begingroup\$

If you load your sprite sheet in programmatically:

private Sprite[] Sprites;

....

Sprites = Resources.LoadAll<Sprite>("SHEET NAME");

The Sprite object has a name property, which you can then use to retrieve a specific sprite by name:

public Sprite GetSpriteByName(string name)
{
    for (int i = 0; i < Sprites.length; i++)
    {
        if (Sprites[i].name == name)
            return Sprites[i];
    }
}

EDIT (alternative method)

You could store it in a Dictionary collection instead, which would provide you with a quicker lookup:

private void LoadDictionary() {
    Sprite[] SpritesData = Resources.LoadAll<Sprite>("SHEET NAME");
    Sprites = new Dictionary<string, Sprite>();

    for (int i = 0; i < SpritesData.Length; i++)
    {
        Sprites.Add(SpritesData[i].name, SpritesData[i]);
    }
}

public Sprite GetSpriteByName(string name) {
    if (Sprites.ContainsKey(name))
        return Sprites[name];
    else 
        return null;
}
\$\endgroup\$
2
  • 1
    \$\begingroup\$ Seems that this is the best idea, even looking online I can't find a nicer solution, kind of a shame. \$\endgroup\$
    – chown
    Jun 11, 2015 at 12:35
  • \$\begingroup\$ @chown A better option could be to save the Sprites in a Dictionary<name, sprite> collection instead (not supported by unity editor though), which would provide you with a much faster byName lookup. \$\endgroup\$
    – jgallant
    Jun 11, 2015 at 12:37

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .