Loading a random object from an array then destroying it and loading another

Hi ! i’m trying to make a game where the background changes randomly while the game progresses.
So i put my gameobjects on an array and i want to randomly load a gameobject and unload the previous one everytime. Any ideas on how to do this ? thanks :slight_smile:

There are various ways of doing this and depends on your game.

you could for example Instatiate randomly a gameObject and destroy the old ones or you could set them Active/!Active, again depends on your game.

set an array of objects like this:

public GameObject [] objectsArray;

set the size and assign the values from the inspector.
You can use the Random to randomly choose you gameObject,and when reaching a waypoint for example,delete the GameObject and place the new one in the new positions.

I don’t know why they took down my answer with the pseudo code because it was fine… but as nksG said you probably are going to want to manage it with an array or a List if you use a list you’re going to have to import the System.Collections.Generic
from their create a function that randomly gets the object from your array/list or increments.

if it’s a background, you might also be changing scenes, so I would also create a singleton for a gamemanager. That way when you changes scenes you are able to keep the script alive/active. Whoever Evil-Tak is took down my answer on how to setup singelton so you’ll have to look that up elsewhere I guess. sorry, don’t know why they don’t allow pseudo code on a coding site…

another way is to use a blend tree and animations, or even the state machine (mecanim).

I would suggest trying each one.

I would suggest not destroying objects but setting them active/inactive via a function call .SetActive([true]|[false])

If it’s just a background that is changing, you probably could setup so the object isn’t being destroyed at all but are just changing colors or the sprites that are being rendered.

Thank you for your answers . I managed to do what i wanted. I’m new to unity so dont hesitate if you have any suggextion to improve my code.

    // set a random counter to array.lenght-1
        i = Random.Range(0, 3);
       // get the character's position
        Vector3 playerPos = GameObject.Find("Player").transform.position;
        float x = playerPos.x;
        float y = -2;
        float z = 0;
        Vector3 pos = new Vector3(x, y, z);
        //Instantiate a random background from the array 
        currentScene = Instantiate(Scenes*, pos, Quaternion.identity) as GameObject;*

// move the currently instantiated background to the last case of the array
// and shift the remaining backgrounds to the left
aux = Scenes*;*
for (int j = i; j <=Scenes.Length -2 ; j++)
Scenes[j] = Scenes[j + 1];
Scenes[Scenes.Length - 1] = aux;
// Destroy the old background when the new one is loaded
if (currentScene.name != oldScene.name)
oldScene = currentScene;`