I made a game where the map is a set of corridors generated randomly using a lot of Random.Ranges, I got no problems until I got to making the multiplayer, I needed a Seed generated by the Host server and then passed to the other player connected (it’s a Co-Op game, no more than 2 Players), I succesfully created a Script that resets the seed any time I press the button to reset the Map. However, my map is not random anymore, Unity generates only 3 or 4 random different sequencies and then starts repeating them each time I restart the Map;
Now my question, Can I write a Script which creates a totally random seed that generates always different sequencies of corridors? Or do I need to write my own random seed generator? If I need to, what’s the code to make it work?
The answer by @Aswissrole still gave me non-unique seeds when generating many seeds in a loop. My solution was to use the states of the Unity Random class, to have a single “state” or “generator” for only generating seeds, while not affecting other generator states:
private static Random.State seedGenerator;
private static int seedGeneratorSeed = 1337;
private static bool seedGeneratorInitialized = false;
public static int GenerateSeed()
{
// remember old seed
var temp = Random.state;
// initialize generator state if needed
if (!seedGeneratorInitialized)
{
Random.InitState(seedGeneratorSeed);
seedGenerator = Random.state;
seedGeneratorInitialized = true;
}
// set our generator state to the seed generator
Random.state = seedGenerator;
// generate our new seed
var generatedSeed = Random.Range(int.MinValue, int.MaxValue);
// remember the new generator state
seedGenerator = Random.state;
// set the original state back so that normal random generation can continue where it left off
Random.state = temp;
return generatedSeed;
}
This pretty much guaranteed to generate only unique seeds. Of course, ignoring the infinitesimally small chance a clash is generated. To solve this I’d say keep track of a list and keep generating until a unique number is generated, but in my case that chance is small enough to not need such a list.