I want to shuffle the numbers in my array
variable once, so I called my Shuffle
method from Start()
.
I then attempt access the sh
Move int[] array = { 1, 2, 3, 4, 5, 6, 7, 8};
outside the Start function.
private System.Random _random = new System.Random();
float sec;
float timecount;
float starttime;
int[] array = { 1, 2, 3, 4, 5, 6, 7, 8 };
void Start()
{
starttime = Time.time;
Shuffle(array);
foreach (int value in array)
{
Debug.Log(value);
}
}
void Update()
{
//time
timecount = Time.time - starttime;
sec = (timecount % 60f);
if (Mathf.Round(sec) == 3f)
{
//access shuffled array
Debug.Log(array[3]);
}
}
//for shuffle number from array
void Shuffle(int[] array)
{
int p = array.Length;
for (int n = p - 1; n > 0; n--)
{
int r = _random.Next(0, n);
int t = array[r];
array[r] = array[n];
array[n] = t;
}
}
EDIT: Not related to your question.
There is a bug in your Shuffle function. array[0]
will always remain 1 and will never change. To fix this, replace int r = _random.Next(1, n);
with int r = _random.Next(0, n);
in the Shuffle function.