Changing a sprite using code won't work

Hi,

I’m trying to change the sprite of a UI Image. I want it to be a random choice between 9 images, named Meme1.png till Meme9.png.
They’re all in the /Assets/Resources/Sprites/Server folder.

My code is:

private void ChangeServerSprite() {
    int rndSprite = Random.Range(1, 9);
    string spriteToLoad = "/Sprites/Server/Meme" + rndSprite;
    Sprite sprite = Resources.Load(spriteToLoad, typeof(Sprite)) as Sprite;
    server.GetComponent<Image>().overrideSprite = sprite;
}

The method is being called, the random number works just fine (tested with breakpoints), but the Sprite called sprite is always null.
Any help would be MUCH appreciated!

I think that would be better to just create an public array of images within the script itself, attach all the 9 images to that array and then use a random range to pick the index of the array.

Hey that’s a good idea! Will try.

1 Like

Let me know if it does work, I would be happy to help :slight_smile:

It worked, thanks mate!! :slight_smile:

1 Like

Awesome! :smile:

Privacy & Terms