Search Unity

  1. The 2022.1 beta is now available for testing. To find out what's new, have a look at our 2022.1 beta blog post.
    Dismiss Notice
  2. Welcome to the Unity Forums! Please take the time to read our Code of Conduct here to familiarize yourself with the rules and how to post constructively.

Random.NextInt return same value everytime

Discussion in 'Project Tiny' started by dallin_unity, Sep 7, 2021.

  1. dallin_unity

    dallin_unity

    Joined:
    Dec 18, 2019
    Posts:
    38
    Hi guys, I got a problem with generating random int number, it returns same value everytime, here is the code

    Code (CSharp):
    1. using Random = Unity.Mathematics.Random;
    2. private Random randomGenerator;
    3. protected override void OnStartRunning(){
    4.             randomGenerator = new Random();
    5.             randomGenerator.InitState();
    6. }
    7.  
    8. private void someFunction(){
    9.             int randomStartX = randomGenerator.NextInt(1, worldCreator.width -1);
    10.             int randomStartY = randomGenerator.NextInt(1,
    11.             worldCreator.height -1);
    12. }
    13.  
    randomStartX and randomStartY always return 7 and 7 everytime, I don't know why.
    Thanks.
     
  2. GilCat

    GilCat

    Joined:
    Sep 21, 2013
    Posts:
    675
    You need to seed the random based on a value that will be different every time you initialise it.
    eg:
    Code (CSharp):
    1. random = new Random((uint)System.DateTime.Now.Millisecond);
     
    dallin_unity likes this.
  3. dallin_unity

    dallin_unity

    Joined:
    Dec 18, 2019
    Posts:
    38
    Thanks, it is working
     
  4. djsell

    djsell

    Joined:
    Aug 29, 2013
    Posts:
    77
    dallin_unity and GilCat like this.
  5. dallin_unity

    dallin_unity

    Joined:
    Dec 18, 2019
    Posts:
    38
    GilCat and djsell like this.
unityunity