- Home /
How to randomly put my game objects in 3 previously setup vectors2 without repeating 2 objects in the same Vector2?
I'm trying to make a level that the objects spawn randomly between 3 vectors2, each one containing a different object. The problem is that i can't think of a way to do this without 2 objects getting on the same position. Is there any way to use random.range that it would not repeat?
Answer by Zooow · May 24, 2017 at 01:44 PM
No there's no parameter in Random.Range() to make it not repeat. So you need to manage your random logic.
Here's how you can do it:
store your vector2 position in a List
randomly draw your first vector2 position from the list
remove the vector2 position your draw from the list
goto 2 ^_^
in code, it would be something like that :
// create your list
List<Vector2> positionList = new List<Vector2>();
// add your vector 2 positions in the list
positionList.Add(Vector2.left);
positionList.Add(Vector2.right);
positionList.Add(Vector2.down);
// randomly draw your first position
int positionIndex = Random.Range(0, positionList.Count);
Vector2 rndPosition = positionList[positionIndex];
//... assign the rndPosition...
// then remove this vector2 position form the list, so your list contains only valid positions
positionList.RemoveAt(positionIndex);
Your answer
Follow this Question
Related Questions
List and random Sprites? 1 Answer
My sprite doesn't render on scene view and game view 2 Answers
Random.Range(..) not working 1 Answer
How to display a random sprite? 0 Answers