- Home /
Three Random Objects From Array Without Repeat
I'm trying to get three different objects to instantiate randomly in three locations so that every time I start the game the objects spawn in different places. As of right now, I was able to figure out how to get the objects to spawn at each location without any objects overlapping each other. However, the problem I have now is that the same object spawns three times.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RandomItemsThree : MonoBehaviour {
public GameObject[] slideSpots;
public GameObject[] objects;
GameObject randomObjects;
GameObject firstObject;
GameObject secondObject;
GameObject thirdObject;
int objectCount;
int spawnCount;
private void Start()
{
MyMethod();
}
void MyMethod ()
{
int spawn = Random.Range(0, slideSpots.Length);
int stuff = Random.Range(0, objects.Length);
randomObjects = objects[stuff];
firstObject = GameObject.Instantiate(randomObjects, slideSpots[0].transform.position, Quaternion.identity);
secondObject = GameObject.Instantiate(randomObjects, slideSpots[1].transform.position, Quaternion.identity);
thirdObject = GameObject.Instantiate(randomObjects, slideSpots[2].transform.position, Quaternion.identity);
}
}
Answer by Jordash · Oct 31, 2018 at 01:43 AM
You're picking a random number with
int stuff = Random.Range(0, objects.Length);
Then assigning randomObjects as the index of stuff into the objects array
randomObjects = objects[stuff];
But because you only generate stuff as a random number once and assign randomObjects once it will always be the same random number and therefore same object. You'll need to have a copy of that code between each spawn for a new random number and object each time.
As a side note, if you do not want duplicates you can do a while loop for the random number generator checking against the last numbers, or copy the array and do a Fisher-Yates shuffle then pick the first three, or randomly pick from a list and remove spawns/objects when chosen. Make sure you check there are more than three items in the array for these approachs though.