How would I go about making random car prefabs drive up and down a road at varying speeds? (for example, crossy road)

I have created a few 3D vehicles, I have also created a road with two lanes. Ultimately I would like cars travelling in opposite directions and at varying speeds. I would also like each car which travels by to be a random car prefab.

I have some basic idea e.g. creating spawn point game object either end of the road and telling each prefab to travel from A to B.

Also using a random number selection function to determine which prefab is instantiated maybe?

I would be very grateful if someone could point me in the right direction, or at least to a helpful resource.

Many thanks,

Freddie

Hi,

Sorry if I misunderstood the Question.

Yes you can easily use that approach that Spawn a car at the end of the line ( i.e. Outside of Screen) to make the natural effect.

To Spawn the Random cars place all the cars in the Particular folder in the Resources ( like “Resources> AvailableCars”). Now you have to Instantiate the cars randomly from this by this line of code. ( this is not the best approach but if you are not too much familiar wid the code then just name the prefabs as 0,1,2, … upto N numbers). Then Generate the random number.

public int totalNumberOfItemsInAvailableCars;
   
// write this where you want to Instantiate the car
int randomNum = Random.Range(0, totalNumberOfItemsInFolder)
Object objTemp = Resources.Load ("AvailableCars/" + randomNum);
Instantiate (objTemp) as GameObject;

The above code is for spawning random cars. Now for the random speed the trick is there must be one car in the lane. This is because if there is more than one car in single lane then suppose the first car is slow and second one is faster than the second car will collide with the first one which is not the desired output.

So same approach will be present there for the speed. Write the below mentioned line of code where you are handling the speed & positioning of the car.

float minSpeedOfTheCar = 0.5f;
float maxSpeedOfTheCar = 3f;
    
float randomSpeed = Random.Range(minSpeedOfTheCar, maxSpeedOfTheCar);

Now assign the value of ‘randomSpeed’ to the carSpeedHandler variable or use directly this variable as the carSpeed.

Thanks