Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

UnityEngine.Random - multiple objects per scene?

Discussion in 'Scripting' started by Twin-Stick, Sep 14, 2016.

  1. Twin-Stick

    Twin-Stick

    Joined:
    Mar 9, 2016
    Posts:
    111
    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!
     
  2. Boz0r

    Boz0r

    Joined:
    Feb 27, 2014
    Posts:
    419
    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.
     
    Bitcore likes this.
  3. takatok

    takatok

    Joined:
    Aug 18, 2016
    Posts:
    1,496
    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.

    Code (CSharp):
    1. System.Random rngA;
    2. void Awake()
    3. {
    4.          int seed = 5;
    5.          rngA = new System.Random(seed);
    6.  
    7. }
    8.  
    9. // then in other functions
    10. rngA.Next(0,100); // returns an int
    11. rngA.Sample();  // return a float between 0.0 and 1.0
    12.  
    13. // its slightly tricky to get a float between A and B
    14. // compared to the Unity built in random Range
    15. rngA.Sample() * (float)(B-A) + (float)A;
     
    Boz0r likes this.
  4. Boz0r

    Boz0r

    Joined:
    Feb 27, 2014
    Posts:
    419
    Yeah, do this instead.
     
  5. Twin-Stick

    Twin-Stick

    Joined:
    Mar 9, 2016
    Posts:
    111
    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!
    :)