I was having a problem with Random.Range, I needed a Random that didn’t repeat any number before all the numbers were chosen. Since there is no built in method that takes care of that, I created my own. Bellow is the script I created. Does anyone has a better solution?
using UnityEngine;
using System.Collections;
public class ArrayTest : MonoBehaviour
{
private bool[] paramArray = new bool[15];
// Use this for initialization
void Start ()
{
ResetArray (ref paramArray);
}
// Update is called once per frame
void Update ()
{
}
public int GetRandom(ref bool[] refArray)
{
int randomLenght,arrayIndex;
bool foundIndex = false;
randomLenght = refArray.Length;
arrayIndex = Random.Range (0, randomLenght);
if (IsArrayFull (refArray))
{
ResetArray (ref refArray);
refArray [arrayIndex] = true;
} else
{
while (!foundIndex)
{
if (!refArray [arrayIndex])
{
refArray [arrayIndex] = true;
foundIndex = true;
} else
{
if (arrayIndex == randomLenght - 1)
{
arrayIndex = 0;
} else
{
arrayIndex++;
}
}
}
}
return arrayIndex;
}
public void ResetArray( ref bool[] arrayToReset)
{
int arrayLenght,i;
arrayLenght = arrayToReset.Length;
for (i = 0; i < arrayLenght; i++)
{
arrayToReset [i] = false;
}
}
public bool IsArrayFull( bool[] arrayToTest)
{
bool isFull = true;
int arrayLenght, i;
arrayLenght = arrayToTest.Length;
for (i = 0; i < arrayLenght; i++)
{
if (arrayToTest [i] == false)
{
isFull = false;
}
}
return isFull;
}
}
The logic of it is that I have a boolean array where I store all used numbers, the index of that array can also be used for other things. For example, my game have 15 targets, and 5 types of targets. I have one array with the position of the targets (predefined) and another with the type of targets used. For each of this arrays, I have an equivalent boolean array.