Spawning System

So I’m making a game where you are a grenade trying to cross a road without getting hit by any cars. Kinda like crossy road. Here is how it looks like:

/;l

So I cant think of a good system that would spawn cars, like how would I manage the speed? By animation or add force? How would I say where to spawn the cars and when. When to destroy the cars, when to spawn the road etc… Really been struggling with this…

Thanks in advance :smiley:

Cars speed

I would recommand you to use
transform.position += Vector3.forward*speed.
If you want to have random speeds, you can do something like this :

//script on every car
float thisCarSpeed;
float defaultSpeed;
float randomValue;
void Start()
{
    thisCarSpeed = Random.Range(defaultSpeed-randomValue, defaultSpeed+randomValue)
}

void Update()
{
    transform.position += Vector3.forward*thisCarSpeed;
}

So each car has its own random speed in range.



Spawning system

I would use a coroutine like this :

 //global script which manage car speawning from car's prefab.
    
public GameObject[] carPrefabs; //all your car prefab (because it seems like you have several cars prefab)
public float spawningRate; //delay between each car spawn
public Tranform[] spawningPoints; //create some points on each road. Then they will get forward with the camera. I assume that your camera never go back.

public float spawningOffset;

void Start()
{
   StartCoroutine(Spawning());
}

void Update() //moves the spawn points along the road
{
   //keep the 'foreach' which works !!! the first works if the road is along the x axis and the second works if the road is along the z axis. I dunno in wich orientation you set up the road.

   //FIRST

    foreach(Tranform point in spawningPoints)
     {
          point.position = new Vector3(Camera.main.tranform.position.x+spawningOffset, 0, 0);

     }
// THE SECOND
 foreach(Tranform point in spawningPoints)
     {
          point.position = new Vector3(0, 0,Camera.main.tranform.position.z+spawningOffset);

     }
}

IEnumerator Spawing ()
{
   while(true) //makes the while repeating itself forever.
  {
       Transform randomSpawningPoint = spawningPoint[0, 
       spawningPoint.Length];

       Vector3 spawingPosition = randomSpawningPoint.position;
      
       Instantiate(carPrefabs[Random.Range(0, carPrefabs.Length), spawningPosition, Quaternion.identity] //the Quaternion.identity can be wrong, it depends of how do you created your game (in wich orientation your road is ?)
       //make sure the prefab have the script i also wrote about (cars speed)

       yield return new WaitForSeconds(spawningRate);
       yield return new WaitForEndOfFrame(); //this one avoids an infinite frame (= game crash) if spawningRate = 0)
  }
}

I hope this is useful
Tell me if you get an error with it, i didn’t test it

@SiniKettu_ I am getting errors with: spawningPoint[0, spawningPoint.Length]; When I remove the zero I don’t get any errors. Thanks!