UnityEngine.Random - multiple objects per scene?

Hi there fellow coders!
A (hopefully!) quick question for you… With the unity implementation of the Random class, is it possible to have multiple objects of this inside a scene, for example…

Class A has it’s own Random object named rngA
Class B has it’s own Random object named rngB

Both have their own unique seed to produce different results.

Or - is it static for the whole scene and would a better approach be to have a sceneManager gameObject with a function to set and reset the Random.InitSeed(“SEED”) when different classes call it?

I hope that actually makes sense to someone!

If you want to make sure you get the same pseudo-random results for each class, I think you have to save Random’s state on the class. Random is a static class, so you can’t have one for each object.

1 Like

A simpler approach if you really want 2 classes with unique seeds is just use System.Random. It works pretty much the same as Unity’s, but it isn’t static. You can declare you own instance of it in each class with their own seeds.

System.Random rngA;
void Awake()
{
         int seed = 5;
         rngA = new System.Random(seed);

}

// then in other functions
rngA.Next(0,100); // returns an int
rngA.Sample();  // return a float between 0.0 and 1.0

// its slightly tricky to get a float between A and B
// compared to the Unity built in random Range
rngA.Sample() * (float)(B-A) + (float)A;
1 Like

Yeah, do this instead.

Thanks for all the comments guys!
I actually did start with System.Random first - but swapped over to Unity’s implementation to take advantage of the other cool functions such as Random.ColorHSV() (which yea let’s be real, isn’t all that hard to do yourself… )

Thanks again for the input!
:slight_smile: