Random Determinism

This is simple but perhaps worthy of a quick post.

You want something that is random, something that utilises the random number generator but is also reproducible.  Perhaps you want to be able to generate something using random numbers, and keep generating it until your happy with the result.  At this point you want to be able to save it and reproduce the exact same result.

The random number generator System.Random can be seeded with a value and whilst the values following a particular seed will appear random they will be deterministic, in that the sequence will be the same each time.

Typically if you don’t want that behaviour you would seed the generator with a time dependent seed such as the current time and this is what happens if you create it with default construction.  As the current time is constantly changing and is never the same this means that the sequence of numbers will be different each time.

In one of my recent Unity projects I wanted the reproducible randomness so I created a variable to store the seed, an edit box to set the seed and a button to randomise the seed:

2

So now I can create random geometry but freeze it and reproduce it when I have something I’m happy with.

1

This is a pretty basic technique but worth knowing.

Leave a Reply

Your email address will not be published. Required fields are marked *