Home > Net >  How to get some random numbers printing continually in the console?
How to get some random numbers printing continually in the console?

Time:09-22

My problem is that when I am trying to use Unity to spawn some objects at randomized locations, for some unknown reason, the location of those spawned objects is the same location.

I tried to add Thread.Sleep() to my code and the location will be randomized.

Here is an example:

class Program
{
    static void Main(string[] args)
    {
        var mytest = new Program();

        Console.WriteLine(mytest.test());
        Thread.Sleep(500);
        Console.WriteLine(mytest.test());
        Thread.Sleep(500);
        Console.WriteLine(mytest.test());
        Thread.Sleep(500);

    }

    public int test()
    {
    Random random = new Random();
    int testrandom = random.Next(5, 100);
    return testrandom;
    }

}

I don't want to use Thread.Sleep() all the time, is there a way to get past this problem?

While using debugging, I found that without using Thread.Sleep(), the local variable testrandom will be randomly updated as testrandom = 30,testrandom=32,testrandom=13..., but the result is different, the result is testrandom=30 and repeats itself 3 times. Can someone tell me why is this happening? Maybe it runs too fast?

CodePudding user response:

.NET Random class is seeded by system clock if no explicit seed is given, so if you create new instances in short time apart from each other each instance will give you same number. This is also reason why adding sleep between calls to mytest.test() mitigates problem, as system clock has advanced by the time Thread.Sleep is over. You should reuse same instance of Random, and use that instance every time:

class Program
{
    private Random random = new Random();

    static void Main(string[] args)
    {
        var mytest = new Program();

        Console.WriteLine(mytest.test());
        Console.WriteLine(mytest.test());
        Console.WriteLine(mytest.test());
    }

    public int test()
    {
    int testrandom = random.Next(5, 100);
    return testrandom;
    }

}

Also, you can declare your test() method and Random instance as static, so you don't have to create instance of Program-class:

class Program
{
    private static Random random = new Random();

    static void Main(string[] args)
    {
        Console.WriteLine(test());
        Console.WriteLine(test());
        Console.WriteLine(test());
    }

    public static int test()
    {
        int testrandom = random.Next(5, 100);
        return testrandom;
    }

}
  • Related