Setting the randomizer seed

Before we begin, let’s describe how the Random class normally works.  You use Random.Range(), and Unity picks a plants a seed based on the computer clock- the number of milliseconds that have passed 12 AM.  The seed is then put in an algorithm which creates the “random” number.

Since milliseconds are fast, every time you use Random.Range(), the number changes every time you use it.


Now then…why would you want to override the seed?

One application comes to mind.  Let’s say you’re making a bullet hell game where you should eventually be able to predict the enemy’s fire.  Let’s say you’ve got 1,000 fireballs that rain from the sky and their location may seem random the first time you attempt the boss, but will be the same after attempting the boss over and over again, so after several attempts you learn the pattern.

Now, there are two ways you can do this:

1.) Hardwire all 1,000 of those locations or

2.) Use the Random.Range after setting the seed.



So the code would be something like this.  And yes, I have tested this in Unity and it does indeed create the same pattern every time.

IEnumerator CreateBullets()
  yield return new WaitForSeconds(2f);
   for (int i = 0; i < 2000; i += 2)
     float x = Random.Range(-10f, 10f);
     Random.InitState(i + 1);
     float z = Random.Range(-10f, 10f);
     Vector3 newPos = new Vector3(x, 50f, z);
     GameObject bullet = Instantiate<GameObject>(bulletPrefab, newPos + transform.position, Quaternion.identity) as GameObject;

     yield return new WaitForSeconds(0.2f);


So there you have it.  That is how you override the seed.


That’s all for now.  Rock on, guys.




Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s