I’m working on an infinite runner where you control a car and have to dodge other vehicles coming your way. I know, really creative right?
I’ve got the movement already figured out, my problem comes when trying to spawn the cars that act as obstacles. I’ve made a simple script that spawns a car and removes it when it’s outside of the player’s view.
public GameObject[] cars; //List of all car prefabs
private Vector3[] spawnLocations = {new Vector3(-7.45f, 8, 0), new Vector3(-4, 8, 0), new Vector3(0, 8, 0), new Vector3(4.5f, 8, 0), new Vector3(7.5f, 8, 0)};
[Header("Time manager")]
public float spawnTime; //Interval between spawns
private float currentTime = 0;
private GameObject currentClone;
private bool spawned;
[Header("Cars movement")]
public float moveSpeed;
private float DestroyLocation = -6.4f;
// Update is called once per frame
void Update()
{
currentTime += Time.deltaTime;
if (currentTime >= spawnTime && !spawned)
{
currentTime = 0;
currentClone = CarSpawn(cars, spawnLocation); //Function to spawn.Not required for example
spawned = true;
}
else if (spawned)
{
currentClone.GetComponent<Rigidbody2D>().velocity = new Vector2(0, moveSpeed);
if(currentClone.transform.position.y <= DestroyLocation)
{
DeleteCar(currentClone); //Function to Destroy. Not required for example
spawned = false;
}
}
}
This kind of works. It does spawn a car and destroys it when no longer needed. The problem comes from the fact that I can only spawn 1 car at a time. How can I rewrite the code to handle multiple cars on screen