jeudi 30 juillet 2020

Two object keep getting the same random number in Unity [duplicate]

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);
    }


}

}




Aucun commentaire:

Enregistrer un commentaire