Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

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.

share|improve this question

2 Answers 2

up vote 2 down vote accepted

I'm guessing each object has it's 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.

share|improve this answer
    
Really thanks. I changed that seed will be index of object in List. I'll at your note, later. Thanks once again. –  marcel Aug 13 '12 at 20:36

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);
share|improve this answer
    
This is helpfull too. Thanks, but i used Darcara answer. –  marcel Aug 13 '12 at 20:41

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.