Choose random background at start

I have several different backgrounds I want to use, but I don’t know how to make the sprite render change to a random one of my backgrounds. I was thinking of using an array and putting my backgrounds in it and the choosing a random one at start, but I have no idea how to do it. Any help would be appreciated.

1 Answer

1

Try this,

using UnityEngine;
using System.Collections;

public class RandomBackground : MonoBehaviour {

	public SpriteRenderer backgroundSpriteRenderer;
	public Sprite[] backgroundSprites;

	// Use this for initialization
	void Start () {
		backgroundSpriteRenderer.sprite = backgroundSprites [Random.Range (0, backgroundSprites.Length)];
	}

}

Make sure you assign the spriteRenderer, and background sprites in the inspector.

Thanks! it works perfectly.

–

Actually how and where i add this C# script if i have already few background sprites in my game project?

–

Just put the script on your main camera or something and assign the sprite renderer to the background. If you have multiple background sprites in one scene, you should add an array of sprite renderer variables or just multiple renderer variables and make an int that you call at start with the random.range and then plug that into the brackets for each of the sprite renderers

–

Got it, thanks :)

–

Could you tell me more specific about this, please? For random changing background, I added above script on my main camera and setting like capture image.. What can I do for make it? ![alt text][1] [1]: /storage/temp/60531-12.png

–