[Solved]Creating an Array of Randomly Selected Backgrounds

Hey everyone,
I am trying to script the selection of a random background image on my canvas from an array of background images. I’ve tried a couple of things so far. Here is my current attempt:

public class BackgroundChanger : MonoBehaviour {

    private Image background;
    [SerializeField]
    private List<Image> bgImage = new List<Image>();
	void Start ()
    {
        background = GetComponent<Image>();
        Image randomBG = bgImage[Random.Range(0, bgImage.Count)];
        background = randomBG;
    }

In this attempt, I am not able to add my Images to my Array in Unity. I have also tried using Sprite instead but that doesn’t seem to change the background as desired. Any help is appreciated.

Got it! Switched the Array to a Sprite and was able to change the sprite of the background.

private Image background;
[SerializeField]
private List<Sprite> bgImage = new List<Sprite>();
void Start ()
{
    background = GetComponent<Image>();
    Sprite randomBG = bgImage[Random.Range(0, bgImage.Count)];
    background.sprite = randomBG;
}
1 Like

Nice find and interesting idea for game backgrounds - thanks for sharing :slight_smile:

1 Like

Privacy & Terms