- Home /
Non Repetative Random.Range
Is it possible to randomize without repeating the same value again? As you can see in the below script, If I instantiate the game object from array, Game objects are repeating, I want the game object to be shuffled not repeated. Any help would be appreciated. Thanks in advance.
public GameObject[] answerPrefabs;
public Transform[] spawnPos;
public void Start()
{
for(int i = 0; i<spawnPos.Length; i++)
{
int answerClone= Random.Range(0,answerPrefabs.Length);
Instantiate(answerPrefabs[answerClone],spawnPos[i].position,spawnPos[i].rotation);
}
}
Answer by NeverHopeless · Aug 10, 2015 at 08:40 AM
A possibility to remove the instantiated element from array. I would suggest to use System.Collections.Generic.List<T>
instead. Try like this:
public List<GameObject> answerPrefabs;
public List<Transform> spawnPos;
public void Start()
{
for(int i = spawnPos.Length - 1; i >= 0; i--)
{
int answerClone= Random.Range(0, answerPrefabs.Count);
Instantiate(answerPrefabs[answerClone],spawnPos[i].position,spawnPos[i].rotation);
// Remove the instantiated element from list.
answerPrefabs.RemoveAt(answerClone);
spawnPos.RemoveAt(answerClone);
}
}
Hope it helps!
Awesome. Thanks you very much! I ave a question for you.
If I use my previous method, answerPrefabs.RemoveAt(answerClone); I cant use this as it is not a list right? So how do i remove the repetitive one?
I think you mean Remove() ins$$anonymous$$d of RemoveAt(). The first removes the instance of the object parameter from the list while the second takes an index as a parameter and removes the object from that index in the list.
Your answer
Follow this Question
Related Questions
How to be notified of new GamObject creation? 1 Answer
Unwanted 2nd empty gameobject 1 Answer
2D Array of GameObjects... 1 Answer
NavMesh giving jerky like motion 0 Answers