Setting a random seed for Unity

Over the holidays I’ve been playing with game development in Unity, so I’m going to post a couple of things I’ve discovered that I think are handy. First up: setting a random seed for your game. Not exactly a groundbreaking discovery, but I implemented this early on and it’s game-changing (har har).

I added a method to log what the game’s random seed is and make it easy to set. Now, when I run into a bug, I can immediately reproduce it in subsequent runs.

The code is a short function that I put in my GameManager.cs:

using UnityEngine;

// If you are using System, disambiguate.
using Random = UnityEngine.Random;


class GameManager : MonoBehaviour {
  
  void Awake() {
    // ...
  }

  private void SetSeed(int state=0) {
    if (state == 0) {
      state = System.DateTime.Now.Millisecond;
    }
    Debug.Log("Random seed: " + state);
    Random.InitState(state);
  }
}

Now in GameManager.Awake, I can simply call SetSeed() (or SetSeed(123) if I’m trying to reproduce a specific failure). If I want to come back and debug something later, I can make a note of the seed with the bug report.

System.DateTime.Now.Millisecond returns a number between 0-999, so if you want more possible scenarios you might want to use a different mechanism for generating random seed. However, I liked having a 3-digit seed, since they’re pretty easy to read & remember.

Hope this helps someone!

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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

%d bloggers like this: