- Home /
Determinism problems: Mathf, Unity.Random VS Math, System.Random
My game must be deterministic, but I'm having problems running my tests in the same machine (!). We are using .NET Math and Random (always same seed, of course), and that can be a reason why I lose determinism in different machines. Is that true? Does Unity assure the same results on different machines if I use Mathf and Unity.Random?
I'm doing everything on FixedUpdate, so any clues of why I'm losing determinism in the same machine would be great.
My checksum simply sums x,y,z of the position of my main GameObjects.
Answer by ScottMcG · Nov 08, 2011 at 10:21 PM
Both System.Math.Random and UnityEngine.Random are platform/machine independent. Assuming you give it the same seed each time, every build of your game on every platform will produce the same random sequence. If you still don't see deterministic results, something is amiss in your code (seeding, race conditions, flow differences, etc). Here are the diffs that I know of... and reasons why I prefer UnityEngine.Random for game code.
UnityEngine.Random has static functions / properties. Any time you need a random number, just use UnityEngine.Random.value. System.Math.Random is a regular class that must be instantiated and stored by any classes trying to use it.
UnityEngine.Random produces floats, System.Math.Random produces ints or doubles.
For anything that's at all complex, it's better to use System.Random. (Probably that was just a typo, but it's not System.$$anonymous$$ath.Random.) The reason is that UnityEngine.Random is "global"--any call will change the outcome for the next call, so it's not really that hard to screw up your code by adding a function that uses Random, which interferes with the sequence for other functions also using Random. With System.Random, you can have "local" seeds, so to speak, so functions can work independently without having to worry about it. That also makes it easier to mix pseudo-random code with "real" random code.
Yes, that's why I ended up creating my own System.Random singleton to use in the whole project without messing with any possible call from outside scripts. Anyways, thanks for the info, Scott$$anonymous$$cG, the indeter$$anonymous$$ism I've been facing were arisen from other reasons, not the Random, like you said.
$$anonymous$$ay be is out of topic. But which library use Unity to generate random numbers? Is $$anonymous$$arsene Twister ? Is the local machine random system?
Ciao
Answer by tucano · Apr 18, 2012 at 09:44 AM
I am working on a library to generate PNRG (pseudo random numbers) with Mersenne Twister: https://github.com/tucano/UnityRandom