10

Setting a random seed for Unity – Kristina Chodorow's Blog

 2 years ago
source link: https://kchodorow.com/2022/01/10/setting-a-random-seed-for-unity/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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!

Posted bykchodorowJanuary 10, 2022Posted inUncategorized


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK