1
\$\begingroup\$

i need help with some "scary" thing. I'm creating some objects in foreach loop. Each object has implemented in Update function random change of position.

But while i'm creating this objects in foreach loop, each object gets the same random position, and i don't know why. Please help me.

For better explanation:

List<Object> objects;

in initialization:

objects = new List<Object>();
objects.Add(new Object());
objects.Add(new Object());
objects.Add(new Object());

and Update and Draw function:

foreach(var obj in objects)
    obj.Update(); // obj.Draw();

in Object Update function:

Position.X = rand.Next(width);
Position.Y = rand.Next(height);

The problem comming in launched game, where I can see only one object, instead of three. All that objects has same position, so they are covered by each other.

\$\endgroup\$

2 Answers 2

2
\$\begingroup\$

I'm guessing each object has its own System.Random object initialized with the same seed? Try making it static for now and see if that fixes the problem.

Note: System.Random is not thread-safe, see: Getting random numbers in a thread-safe way for a solution, should you need it.

\$\endgroup\$
1
  • \$\begingroup\$ Really thanks. I changed that seed will be index of object in List. I'll at your note, later. Thanks once again. \$\endgroup\$
    – marcel
    Aug 13, 2012 at 20:36
1
\$\begingroup\$

Look at this page.

According to the example in the "remarks" section, seperate instances of the class Random result in the same values when Random.Next() is called.

According to the documentation, you can solve this by having just one Random class and calling Next() when you need a random number. So the object classes in your code shouldn't have their own Random.

You can modify Update() to solve this:

public void Update(Random rnd) {

Position.X = rnd.Next(width);
Position.Y = rnd.Next(height);
}

and call Update like this:

Random rand=new Random();

foreach(var obj in objects)
obj.Update(rand);
\$\endgroup\$
1
  • \$\begingroup\$ This is helpfull too. Thanks, but i used Darcara answer. \$\endgroup\$
    – marcel
    Aug 13, 2012 at 20:41

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .