I have a SpriteSheet which I imported in Unity so I have a basic Texture2D asset which is separated in multiple sprites which are named like (sprite_0,sprite_1, etc.) Im trying to set the sprite of my SpriteRenderer in code but I want to be able to load a sprite dynamically, not have to link it in the script directly. So I have a Resources and a Textures folder within it. I’ trying to get the sprite by doing Sprite s = Resources.Load(“Textures/sprite_0”) as Sprite. But it is always null. In fact, when I want to load the “Base” sprite named “Sprite”, it recognize it as a Texture2D type, but when I want to load a specific sprite in my texture like sprite_0, it just can’t find it at all. I have my texture type set to Sprite, and Mode to multiple. Does anybody have an idea ?. Thanks a lot for your time
Unfortunately in my case, the names do not contain index. I did so: Sprite[] textures = Resources.LoadAll<Sprite>("Textures"); string[] names = new string[textures.Length]; for(int ii=0; ii< names.Length; ii++) { names[ii] = textures[ii].name; } Sprite sprite = textures[Array.IndexOf(names, "textureName")]; But maybe there's a more elegant way?
This is pretty great! Saves you the trouble of putting stuff in a Resources folder, too! (I'm neurotic, and feel sooooo much better if I can keep my folders labeled by type)
So, bad news, actually -- this only works in the Editor. Turns out AssetDatabase is name-spaced to UnityEditor, and so if you include this elsewhere in your code it won't build.
How then to get the desired sprite by name?
– ABCptOnly by index, I suppose. It's not a problem, because name looks like "textureName_spriteIndex".
– Dragon_MaoUnfortunately in my case, the names do not contain index. I did so: Sprite[] textures = Resources.LoadAll<Sprite>("Textures"); string[] names = new string[textures.Length]; for(int ii=0; ii< names.Length; ii++) { names[ii] = textures[ii].name; } Sprite sprite = textures[Array.IndexOf(names, "textureName")]; But maybe there's a more elegant way?
– ABCptWorked like a charm ! Thanks a lot everybody for your time :)
– Siflou@Siflou: Hi, could you post the final code, so we could see how did you solve it, because it's not working for me.. thanks.
– amjadyahya