Search Unity

  1. Unity Asset Manager is now available in public beta. Try it out now and join the conversation here in the forums.
    Dismiss Notice

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:
    40
    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:
    676
    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:
    40
    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:
    40
    GilCat and djsell like this.