- Home /
Choose Random Background During Game
hello everyone . i want to create a 2D game with infinity background . i have 10 different back ground ad i want that the game choose them randomly and select it as the next image that appears during the game . what should i do?
Answer by sadowlight123 · Aug 11, 2017 at 10:10 AM
hello
1-place an empty gameobject and call it "Background"
2-from the inspector add a sprite renderer
3-create and new script called "RandomBackground" and assign t to the "Background" gameobject
4-write the following code :
 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class RandomBackground : MonoBehaviour {
 
     public Sprite[] Backgrounds; //this is an array of type sprite
 
     public SpriteRenderer Render; //this is a variable of type sprite renderer
 
     // Use this for initialization
     void Start () {
            Render = GetComponent<SpriteRenderer>(); 
            /*assigning the Render to the object's SpriteRender, this will allow us to access the image from 
            code*/
            Render.sprite = Backgrounds[Random.Range(0, Backgrounds.Length)]; 
            /*this will change the current sprite of the sprite renderer to a random sprite that was chosen 
            randomly from the array of backgrounds */
         }
     // Update is called once per frame
     void Update () {
 
     }
 }
5-on the inspector , type 10 in the Backgrounds input box , it will open 10 slots for you 6-drag and drop the diffrent background images you need from your project panel respectively to the 10 slots you opened .
this should be it , everytime you will start the scene you will get a different background Please let me know if this helped.
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                