I just wrote my first code for randomising and I’m using seeds to save data.
Now I have the problem that i could spawn random objects inside a boundary of x, y and z, but that is shaped like a cube.
Since I wrote a code to convert the inputted seed into a randomizer, is there a way to use that randomising in “insideUnitSphere” to make the boundaries a sphere?
Maybe something like this (which doesn’t work) :
//Defining a string seed beforehand
System.Random myRandom = new System.Random(seed.GetHashCode());
Vector3 pos = new Vector3(myRandom.insideUnitSphere);
Because otherwise, the Random:insideUnitSphere is completely random, which defies the usage of a seed…
I don’t believe you.
If you’re talking about Unity’s RNG, you can save, restore, or initialize its state. With System.Random, I guess your gripe is that it doesn’t have an insideUnitSphere method, but you could make one this way.
1 Like
I believe your running into the problem that there are 2 different Random classes available to you:
System.Random which is the .Net built in Random Class
UnityEngine.Random which is Unity’s Random Class
Now Sytem.Random does take a constructor that has a seed (like your example), Unity Engine’s random does not it does it like this:
UnityEngine.Random myRandom = new UnityEngine.Random();
myRandom.InitState(seed);
One Quick note, you can avoid having to type out System.Random or UnityEngine.Random to make sure your getting the right one with this line at the top with your using statements:
using Random = UnityEngine.Random;
Another thing to note, is that Random.insideUnitCircle is a static member of the random class. You can’t access it like this:
// This is wrong and will throw a compile error
Random myRand = new Random();
Vector3 pos = myRand.insideUnitSphere;
You have to access it like this:
Vector3 pos = Random.insideUnitSphere;
However you can still initialize this static Random instance like this (so you always get the same points each time you run your code:
using Random = UnityEngine.Random;
public int seed;
void Awake()
{
Random.InitState(seed);
}
void Start()
{
//This will generate the same Vector3 everytime you hit Play
Vector3 pos = Random.unitInsideSphere;
}
Edit: if your using seeds to test your code , I would highly suggest just using the static Random instance. That way one script can call the InitState in its Awake function, than all the other scripts can just call Random.Range(). This way all you scripts can use one copy of random and it will be easy to duplicate results. If you try to instantiate your own copies of random it might be harder to debug and sync them.
1 Like
Perfect!!!
Thanks, and sorry for the stupid questions, I just haven’t had found the Random.InitState yet.
This makes a lot so much easier 
2 Likes