I have a class that randomly creates some objects on the stage, These objects appear at two random points. The problem is Random.Range
has the probability of choosing a point several times in a row, that is, I pick the same point 5 or 6 times. I just want to limit myself somehow, that if Random.Range
chose the same point at most 3 times, it would choose another point.
public ObjectSequence ObstacleSequence;
public float WaitSpawnTime;
public float DistanceFromObstacleIndex;
public Transform[] spawnPoints;
private List<int> Point = new List<int>();
void Start()
{
InvokeRepeating("Spawn", WaitSpawnTime, DistanceFromObstacleIndex);
}
void Spawn()
{
int spawnPointIndex;
do
{
spawnPointIndex = Random.Range(0, spawnPoints.Length);
Point.Add(spawnPointIndex);
} while (SwitchPoint());
if (SwitchPoint())
Point.Clear();
ObjectSequence obstacle = Instantiate(ObstacleSequence,
spawnPoints[spawnPointIndex].position, spawnPoints[spawnPointIndex].rotation);
obstacle.setRandomCurrentChildIndex();
obstacle.CurrentChild.GetComponent<SpriteRenderer>().flipY =
(obstacle.transform.position == spawnPoints[1].position) ? true : false;
}
private bool SwitchPoint()
{
if (Point.Count >= 2)
{
return Point[0].Equals(Point[1]) && Point[1].Equals(Point[2]);
}
return false;
}
I only have two points, so "shuffle" approach (like Randomize a List<T> or many other "unique random" posts) does not work.