I am looking at the best practice for this for a while now. I need to get a random number and I need to check if it is currently in a list and if not insert it into the list and if it is to restart my random number.
for (int i = 0; i < 10; i++)
{
//Get random Number
int randomCheck = Random.Range(0,10);
if(listOfInts[randomCheck] == 0)
{
listOfInts[Random.Range(0,10)] = 1;
}
else
{
//No idea what to put here to re do if statment...
}
}
//Our list of old values.
private List<int> _pastNumbers = new List<int>();
/// <summary>
/// This function will get a random number that has not already been found.
/// If it is unable to get a new number it will return null.
/// </summary>
/// <param name="minValue">The min value the number can be.</param>
/// <param name="maxValue">The max value the number ca be.</param>
/// <returns>a nullable Int</returns>
private int? GetUniqueRandomNumber(int minValue = 0, int maxValue = 10)
{
int? uniqueNumber = null;
int maxLoops = maxValue - minValue;
do
{
uniqueNumber = UnityEngine.Random.Range(minValue, maxValue);
} while (_pastNumbers.Contains(uniqueNumber.Value) || maxLoops-- <= 0);
_pastNumbers.Add(uniqueNumber.Value);
return uniqueNumber;
}
Notes
int? is a nullable type. This basically just means the value can be null. I use it here so you can check when you use this function if we did get a valid number (you could also just set it to -1 but I don’t like that)
Even though I greatly appreciate the help from all the awesome people who posted I have solved my problem on how to get a random number that has not been called easily.
int i = 0;
while(i < numberOfFloorSeed)
{
int randomCheck = GameManager.Instance.GenerateRandomInt(0,floorSize);
if(listOfFloorPos[randomCheck] == 0)
{
listOfFloorPos[randomCheck] = 1;
i++;
}
continue;
}