- Home /
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.
Answer by AjayKhara · Oct 11, 2014 at 03:25 PM
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.
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
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?
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
eulerangle not work with joystick 0 Answers
TPS Camera with Joystick (Android) 0 Answers
How do I get rid of these scripting Errors? 2 Answers
How do I set my android app to landscape mode entirely? 1 Answer