How to generate a different number every time?
I am making a connect 4 game. I made an array that stores all the x-positions for the disks to fall in. I want the computer to generate a random x-position for the disk to fall in every time. Here is my code.
#pragma strict
// Disks that we're playing with public var RedDisk : GameObject;
// Converts array of numbers into a variable private var choices : float[] = [-26.92, -17.8, -9.2, 0, 9.2, 17.8, 26.92]; private var howManyThings : float = choices.length; private var myRandomIndex : float; myRandomIndex = Random.Range (0, howManyThings); private var result : float;
private var PlayerTurn : boolean = false;
// Happens every frame function Update () {
// If it is the enemy's turn, if (PlayerTurn == false) {
result = choices[myRandomIndex];
// Create a red disk in a random spot
Instantiate (RedDisk, new Vector3 (result, 10, 0), Quaternion.identity);
// User can now put his disk
PlayerTurn = true;
}
}
Answer by NoseKills · Jun 28, 2016 at 06:19 AM
Create the random number every time you need it. Not just once when the app starts.
myRandomIndex = Random.Range (0, howManyThings);
result = choices[myRandomIndex];
Your answer
![](https://koobas.hobune.stream/wayback/20220612083735im_/https://answers.unity.com/themes/thub/images/avi.jpg)