- Home /
How to handle Instantiation and Destroying on an infinite runner?
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
Answer by Aisenhein · Jan 17, 2021 at 01:26 AM
Hello, I think with a script in the car is better, so the car it self will self destroy when go of-screen or something, so your manager just need to spawn as many cars (or objects) you want
Other point, a better approach for your case I think is to use a object pool instead of instantiate every car every time, basically with this structure of object pool, you instantiate all cars (or other objects) at the begin when load the scene, and just use and reuse then https://learn.unity.com/tutorial/introduction-to-object-pooling
Thanks! The first option worked just fine. I might try to use object pool later for optimization but for now I can continue just fine.
Your answer
Follow this Question
Related Questions
How to destroy a object when it's off screen and re-instantiate it when it gets back on screen 0 Answers
Cannot destroy instantiated objects 2 Answers
Is it possible to create an instance of a prefab without instantiating it into the scene? 1 Answer
Mouse Methods (OnMouseDown, OnMouseOver etc) stop working after certain circumstances 0 Answers