- Home /
Strange random seed issue with level generation
I am currently working on a game that features random level generation, but have ran into an issue when setting a seed.
This is how I currently set the seed:
seed = time.Hour + time.Minute + time.Second + time.Millisecond + 1101077;
UnityEngine.Random.InitState(seed);
Which, for example, returns a value such as 1101356. If I set the seed to this value and generate a level I get the same geometry each and every time, which is fine. However, when I spawn the enemies and background props, there is this strange flip-flop behaviour.
These are the steps:
1) PRESS GENERATE WITH SEED 1101356
-- Geometry is created
-- Enemies are spawned at random locations
-- Props are spawned at random locations
2) PRESS GENERATE AGAIN WITH SEED 1101356
-- The same geometry is created - as expected
-- Enemies are spawned, this time at different locations - not expected
-- Props are spawned, this time at different locations - not expected
3) PRESS GENERATE AGAIN WITH SEED 1101356
-- The same geometry is created - as expected
-- Enemies are spawned, this time at the same locations from Step 1 - not expected
-- Props are spawned, this time at the same locations from Step 1 - not expected
4) PRESS GENERATE AGAIN WITH SEED 1101356
-- The same geometry is created - as expected
-- Enemies are spawned, this time at the same locations from Step 2 - not expected
-- Props are spawned, this time at the same locations from Step 2 - not expected
5) REPEAT STEP 2
-- Observe the same geometry is created
-- Observe the enemies and prop placements are swapping between their locations from steps 2 to 4
At the moment all I can think of is some form of seed issue. Prior to updating to Unity 2019.1.9 (latest at the time) this has never happened before and I was always able to spawn the same level over and over again.
Any ideas?
Answer by jamiewhitephd · Jul 31, 2019 at 04:13 PM
I managed to solve my problem after some exhaustive testing! It's hard to put into words, so bear with me.
What I do is take an array of prop objects and shuffle them (Fisher-Yates) and then attempt to spawn them at empty spaces. Whilst this works in principle, I was feeding in the referenced array from within the Unity editor, NOT an instance of it, if that makes sense. Therefore, to fix it, I took the original array and copied it to a new instance which is then shuffled in the same order each and every time.
Before, the original array (i.e. the one in the inspector) was being shuffled and from within Unity (bearing in mind the game is not running) I could see the inspector was being updated with the new shuffled values. Hence, my enemies and props were being spawned in different places.