A Problem with loading Sprites for UI from scripts

GetComponent<Image>().sprite = Resources.Load<Sprite>(string.Join("",new string[2] {"Projectiles",DescriptionDataHolder.ProjectileID.ToString()}));

So let me break that down, what it is supposed to do is load a Sprite with the name “Projectiles_#”. My project has the Resources folder with a sprite that is set to multiple and sliced into portions properly. When I set the texture manually it works but this returns a null sprite (just a white cube). DescriptionDataHolder.ProjectileID is an int that is currently either 0,1,or 2 so it should get the sliced sprite with that number right? either Projectiles_0, Projectiles_1, or Projectiles_2 right?

I don’t see an underscore character anywhere. Try making the first parameter of Join “_”.

Didn’t work, I tried a few permutations of this but I just can’t figure out the problem. I used a similar technique to swap the sprite of a GameObject already but for this “Image” component I can’t get it to render anything other than than a square of the color set in the Image component

  1. If you use Debug.Log to output the string you generated, what does it say? As @andymads said, no way will that code give you anything that has an underscore in it.

  2. When loading sprites that are sliced into multiples from a single image, you actually need to use Resources.LoadAll(filename, typeof(Sprite) ) on the MAIN IMAGE name, not the name of the sprite. LoadAll should give you an array of objects, which you can loop through and typecast to Sprites. I believe then you should be able to use .name on each of them to compare to the name you’re looking for.

  1. It returns “Projectiles_0” (The code I put into this thread was one of the revisions that I made trying to fix it, I went back to an older one). But still doesn’t function.

  2. The array LoadAll solution actually works. What I still find strange though is another part of my game just uses the method I originally was attempting. I am now less perplexed about why this one works but instead confused on how my original idea ever worked in the first place. Thanks though.

COyNHM-XAAAwwYk.png

That is my entire workflow

1 Like