Why I Failed to Set Seed to Unityengine. Random

I'm trying to set my own seed to UnityEngine.Random (not System.Random) but it seems that it doesn't work. here are my code and output

void Start()
{
    UnityEngine.Random.InitState(114514);
    Debug.Log(UnityEngine.Random.seed);

    var a = UnityEngine.Random.Range(0f,1f);
    Debug.Log(UnityEngine.Random.seed);

    var b = UnityEngine.Random.value;
    Debug.Log(UnityEngine.Random.seed);

    var c = UnityEngine.Random.value;
    Debug.Log(UnityEngine.Random.seed);
}

output:

114514  
-101807786  
-1953724440  
-628832631

why every time I call Random.value or Random.range, it seems that the seed will change to another?

4

1 Answer

Random number engines are implemented in a way that they calculate a pseudo-random number from the seed given. On top of that, they calculate the seed for the next iteration. From that next seed, the next random number and the third seed will be caluclated. Since we want the second (and all following) iterations to yield results different from the first one, the seed needs to change and can not remain the same.

Calculating a seudo-random number by using a specific seed will allways result in the exact same result. And since the new seed is calculated as pseudo-random as well, the sequence of seeds (and outputs) will allways remain the same. Assigning a seed makes sure that you start this sequence at a defined point and not the default one. If you would start your programm with the seed -101807786, the output would be

-1953724440
-628832631

followed by one more seed (which is the next one in the sequence).

Now, there are different implementations of random number engines which may expose different propertys called seed. The UnityEngine.Random happens to exose the current seed under the name seed while other engines may expose the initial, user defined seed under the name seed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Maya Lin-Takahashi

Maya Lin-Takahashi

Consumer Tech & Gadget Reviewer

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.

Share this article
Twitter Facebook Pinterest