lundi 22 février 2016

C# generating a random number, returns the same result each time

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!




Aucun commentaire:

Enregistrer un commentaire