- Home /
Load specific sprite from sprite sheet
I have a sprite sheet with multiple sprites, how can I load a sprite into my game from my resource folder?
I have this:
type2sprite = Resources.Load<Sprite>(
Settings.typeSpritePath + Settings.getType2(party[i].pokedexNumber).ToString()) as Sprite;
The getType2 will return a type for example "GRASS", and I have a sprite in my sprite sheet called GRASS, how can I take that sprite from my sprite sheet?
What do you mean by sprite sheet? Is it an image with individual tiles for sprites, or an image that you split up in the Sprite Editor? I'm not quite sure what you mean.
Answer by dazzle_wolf · Nov 20, 2015 at 06:19 PM
@Jan_Julius As far as I know, you can't.
I need to do the same thing and I have a workaround for it: You could replace the sprite using its pivot and rectangle. Basically, you would move the UV coordinates used for the sprite rendering to use a different part of the atlas. The problem is that Unity does not allow you to access the texture, pivot or rectangle of a sprite (they are read-only).
So this is how you do it: When packing the sprites into the atlas, I generate a .txt file with the sprite's name, pivot and rect. Then at the start of the game, I load the atlas and the .txt into my UIRepository-class. To switch out a sprite for one in this atlas, you can now get the sprite's pivot and rect using its name. However, the only way to actually do this is to create a new sprite with these attributes at runtime (again, since its read-only). This is really, really slow, though. To lessen the impact of this, I cache the sprites but there is still a huge cost the first time you need it.
If you find a better way of doing this, please let me know :-)