Hi all,
I’ve been testing the random function in Unity and so far, it looks like it isn’t random (or it’s just a pure bad luck).
Simply; I initialize the state of the random function once (by using the InitState function) and give the current milliseconds of the PC as the seed. When the scene loads, the game waits a bit to spawn 2 game objects. After the objects are spawned, I generate 2 random colors and change their colors. I move the objects forward a bit and then destroy them. This process repeats in the game.
Here’s the results:
-
When the game starts for first time, 2 objects are spawned at the same time even though I set their spawn times with Random.Range function. It happens always, every time the game starts for first time. Afterwards, everything is random. But for the first time, the random function always return same float number in the same frame, which is 0.5 in my case.
-
The colors are not random usually. For example, let’s say the first object’s color is set to red. When the object is destroyed and spawned again, the random function returns red color again. After repeating the same color 2-3 times, it generates another color. It may sound like a bad luck, but I generate 3 random numbers to generate a random color, which means the function returns the same pattern 2-3 times.
Here’s the pseudo version of my code:
public static Color GetRandomColor(float minValue, float maxValue)
{
minValue /= 255.0f;
maxValue /= 255.0f;
return new Color(Random.Range(minValue, maxValue), Random.Range(minValue, maxValue), Random.Range(minValue, maxValue));
}
float object1SpawnTime;
float object2SpawnTime;
GameObject object1 = null;
GameObject object2 = null;
private void Start()
{
object1SpawnTime = Random.Range(0.5f, 3.5f);
object2SpawnTime = Random.Range(0.5f, 3.5f);
}
private void Update()
{
object1SpawnTime -= Time.deltaTime;
object2SpawnTime -= Time.deltaTime;
if(object1 == null && object1SpawnTime <= 0.0f)
{
//... Spawn the object and set the 'object1' variable
Color color = GetRandomColor(100.0f, 200.0f);
//... Set the object's color
}
if (object2 == null && object2SpawnTime <= 0.0f)
{
//... Spawn the object and set the 'object2' variable
Color color = GetRandomColor(100.0f, 200.0f);
//... Set the object's color
}
//... Move the objects
if (object1.transform.position.x > 2.0f)
{
Destroy(object1);
object1 = null;
object1SpawnTime = Random.Range(0.5f, 3.5f);
}
if (object2.transform.position.x > 2.0f)
{
Destroy(object2);
object2 = null;
object2SpawnTime = Random.Range(0.5f, 3.5f);
}
}
Why does this happen? Is this because I test the game in the editor? Is this because changing the scene does something to the seed? I don’t understand.