简体   繁体   中英

Random() not generating new random numbers

Any help or insight on this would be appreciated. Still kind of a noob with c#, so please bear with me. Here's my problem:

List<Vector2> vectorList = new List<Vector2>();

for (int i = 0; i < 5; i++)
{
    Vector2 tempVector = new Vector2(i, i);
    vectorList.Add(tempVector);
}

This works fine, the output I get is 5 vectors with the following values: (0, 0), (1, 1), (2, 2).. and so on...

I need to get random positions, so i did myself a little function called RandomizePosition().

for (int i = 0; i < 5; i++)
{
    Vector2 tempVector = RandomizePosition();
    vectorList.Add(tempVector);
}

The output i get from this is 5 vectors, containing all the same positions. I'm guessing there is a referencing problem, or the function get called only once or something. Weird thing is, if I go through each loop in debug mode, the output is what I would expect, 5 vectors with different X and Y values, so i guess the function isn't the problem. (or rather it probably is, but not the randomizing logic inside it).

Any ideas on why this is happening, and some insight on how to fix this? Can't you call a function from a loop? Or how can i make sure the function gets called on each iteration? Thanks!

Here's the RandomizePosition() function, if it can help:

private Vector2 RandomizePosition()
{
   Random rand = new Random();

   int seedX = rand.Next(1, 14);
   int seedY = rand.Next(1, 14);

   int posX = 32;
   int posY = 32;

   if (seedX != 1)
       posX += seedX * 64;

   if (seedY != 1)
       posY += seedY * 64;

   return new Vector2(posX, posY);
}

You haven't shown your RandomizePosition() method, but it is likely that you are calling randomise with the same time seed in quick succession, ie creating the Random object inside your RandomizePosition() method.

To stop this happening create the Random object outside your RandomizePosition() method.

Update : you have now shown the code for RandomizePosition() and that is indeed the problem.

As mentioned by @dlev , the reason you see the expected behavior when you step through the code is that you are causing enough time to elapse for your newly created Random() object to use a new seed (since by default it is based on the current time) .

you have declared the rand variable like this Random rand = new Random(); which sholud not be done make the rand variable a static one and declare it in your class not in your method that time you will not be having such troubles

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM