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

Question Fast Unity.Mathematics.Random Seed

Discussion in 'Scripting' started by Noa3, Apr 2, 2023.

  1. Noa3

    Noa3

    Joined:
    May 29, 2012
    Posts:
    84
    Hi!
    what is the fastest way to get a random uint as seed for the Random method from the Mathematics package.
    should i just read the system time and put it in as uint or is the level time maybe faster?

    my method would look like this for getting the random.

    Code (CSharp):
    1.  
    2.     [BurstCompile]
    3.     public static Unity.Mathematics.Random GetRandom()
    4.     {
    5.         return new Unity.Mathematics.Random(  UINT VALUE HERE );
    6.     }
    7.  
    my thought was, to replace with it the most Unity Engine Random.Range , because its faster this way but maybe i can be wrong?

    thanks for your help!
     
  2. angrypenguin

    angrypenguin

    Joined:
    Dec 29, 2011
    Posts:
    15,509
    If you need to know, then I'd write a script which does each one a few thousand times and check the speed on my target device in a release build, with System.Diagnostics.Stopwatch. If you can't tell the difference then it doesn't matter.

    That being said, with common strategies for getting and using random numbers in games you'd pre-generate a seed for each system and re-use it, rather than getting a new one each time, which means that it doesn't matter how fast it is to generate one. The benefit is that you can then re-use seeds for debugging and other purposes where determinism is useful.

    For instance, instead of "bug X happens once per approximately 10 casts of this spell" it can be "with seed 123, bug X happens on the 7th, 19th, 34th... casts of this spell".
     
    Noa3 likes this.
  3. Noa3

    Noa3

    Joined:
    May 29, 2012
    Posts:
    84
    a same seed would mean everyone of the game would be the same and there is no random.
    so i need maybe to generate a new seed everytime in call the method. but i think i take the Time.realtimeSinceStartup from unity and use this as seed, this do the job i want.
     
  4. angrypenguin

    angrypenguin

    Joined:
    Dec 29, 2011
    Posts:
    15,509
    You can generate it at initialisation time, i.e. when your game loads, as opposed to once per random number.
     
    Bunny83 and Noa3 like this.