- Home /
Get Sprite index in array by filename
I have a Sprite[] filled with 20 sprites. I want to change the current sprite of my gameobject by GetComponent().sprite = someSprite. I have the name (in a string) of the sprite I need to change to. There's a built-in way to search in the Sprite[] array the sprite that's name is the one I have? Something like Array.IndexOf(mySprites, nameImLookingFor); ?
try maybe:
// get sprite name
spriteArray[i].name
If you know how to get sprite name from Sprite object then you can create a searching loop.
Answer by alankemp · Mar 01, 2016 at 11:16 AM
You can use Array.FindIndex to search the array, and pass a predicate telling it what you are looking for. In this case you can do something like this:
int index = Array.FindIndex(spriteArray, s => s.name == nameImLookingFor);
This will either return the index of the sprite that matches the name, or -1 if it can't find it.
Your answer
Follow this Question
Related Questions
2 Animation Clips, 1 Sprite 0 Answers
Override sprite geometry of sprite generated at runtime 1 Answer
Sprites loaded if putted on Inspector variable? 0 Answers
SpriteRender's sprite not changing 1 Answer
How to set sprite size in pixels? 2 Answers