0

I have written code for four different cars, They all have the same code in C#. Their objective is to choose a lane (randomly) and then drive down that lane at a certain speed, however, whenever I execute the code, all the cars pile up on one another in one lane.

I've tried to look for explanations on the internet, but all of them are really outdated.

I am using Unity 2019.4, here is my code. Any help will be greatly appreciated.

if (ypos < -7)
{ // n
    Random rnd = new Random();
    int ran = rnd.Next(1, 5);
    if (ran == 1)
    {
        if (isTouching)
        {
            transform.localPosition = new Vector3(-2.4f, -9.0f, transform.localPosition.z);
        }

        transform.localPosition = new Vector3(-2.4f, 9.0f, transform.localPosition.z);
    }
    else if (ran == 2)
    {
        if (isTouching)
        {
            transform.localPosition = new Vector3(-2.4f, -9.0f, transform.localPosition.z);
        }
        transform.localPosition = new Vector3(0.0f, 9.0f, transform.localPosition.z);
    }
    else if (ran == 3)
    {
        if (isTouching)
        {
            transform.localPosition = new Vector3(-2.4f, -9.0f, transform.localPosition.z);
        }
        transform.localPosition = new Vector3(2.5f, 9.0f, transform.localPosition.z);
    }
    else if (ran == 4)
    {
        if (isTouching)
        {
            transform.localPosition = new Vector3(-2.4f, -9.0f, transform.localPosition.z);
        }
        transform.localPosition = new Vector3(5.0f, 9.0f, transform.localPosition.z);
    }


}
else
{
    transform.localPosition = new Vector3(transform.localPosition.x, transform.localPosition.y - speed, transform.localPosition.z);
}
}
}
Airn5475
  • 2,452
  • 29
  • 51
  • 1
    Please [edit] the question to explain why this particular https://stackoverflow.com/questions/767999/random-number-generator-only-generating-one-random-number explanation is outdated (looks like a duplicate to me). Also make sure to provide [MCVE] of the code as problem shown in the question *does not* create multiple objects. – Alexei Levenkov Jul 30 '20 at 17:05
  • I suspect you are seeding `Random` for each car. From the look of your code it is using the default seed from the system clock. If you declare your cars within a single tick of the clock, they will all have the same seed, with the results you see. One solution is to declare a master `Random` outside the `Car` code, and use that master to provide a new seed for each car. – rossum Jul 30 '20 at 19:31

0 Answers0