0

For a school assignment I am currently working on a small project involving a console application. it fills a grid with random traffic objects (like bicycles and cars).

Every time a traffic object is generated and put into the 2D array it will be given a random direction (1, 2, 3, 4). I used the Random class for this.

For some reason when I compile the project and ask for the information about the object (returns name, type and direction and functions the object may perform) it always seems to give the same direction for all the objects.

The constructor of the TrafficObject class is as follows:

    public TrafficObject()
    {
        Random random = new Random();
        Direction = random.Next(4) + 1;
        charColor = ConsoleColor.White;
        nameGenerator = new NameGenerator();
    }

It does seem to generate a random number each time (I checked that using break points multiple times)...

Return statement:

return "Type: " + TrafficObjects[x, y].GetType().Name + "\nDirection: " + TrafficObjects[x, y].Direction;

I'd give you my whole source code so you could compile it but it consists of around 20 different classes...

If you need any more info or code please say so!

Ayush
  • 41,754
  • 51
  • 164
  • 239
Pim Schwippert
  • 453
  • 7
  • 18
  • 2
    If your call to the constructor `TrafficObject()` is in a tight loop, the `Random` object is being seeded with the same time-based value for each instance. Move the `Random` object outside the constructor, instantiate it once, then each call to `Next()` should return a unique value. – Bob Kaufman Feb 22 '16 at 23:44
  • try to use Direction = random.Next(-1,4) + 1; – Tony Dong Feb 22 '16 at 23:48

0 Answers0