How to recycle obstacles in an Endless Runner?
Hi I am creating an Endless Runner for Android, the problem is that obstacles slow down my game, so I don't know how to get them to recycle since they are created infinitely, and another problem is that they are not destroyed by leaving them behind.
This is my code to randomly generate:
using System.Collections;
using UnityEngine;
public class GenerateCube : MonoBehaviour
{
public GameObject CubeObj;
Vector3 Pos;
bool next;
public float[] posX;
public float[] posZ;
int value = 1;
public int lastpos = 1;
void FixedUpdate(){
next = true;
Generate ();
}
void Generate(){
if (!next)
return;
int i = Random.Range (0, 3);
Pos.x = posX[i];
Pos.z += posZ[i];
GameObject CubeClone = Instantiate(CubeObj, Pos, CubeObj.transform.rotation);
CubeClone.GetComponent<CubeScript>().myNum = value;
CubeClone.transform.SetParent (this.transform);
value += 1;
next = false;
return;
}
public void Message(int i){
if(lastpos == i) {
lastpos += 1;
}
}
}
I hope you can help me, Thanks!
Answer by GDGames0302 · Feb 03, 2021 at 10:32 PM
Hi. As I can see, your character runs on axis z+. So, you can attach a script to the obstacle prefab and create a public Transform playerPos and assign the player Transform to that empty slot. In that script add an update function: void Update(){if (transform.position.z < playerPos - 5(over here you put an offset: for example, you don't want to destroy an object when it is exactly behing the player, you want to destroy the object when it is at a certain distance behind the player and out of the camera view. I put 5 just for example, but you should put what you want) Destroy(this.gameObject);)} You can also implement object-pooling, which means that you don't instantiate and destroy objects, you activate and deactivate the same objects.
Your answer
Follow this Question
Related Questions
How do I randomly generate two obstacles in a 3D endless runner with 1 gap to go through? 1 Answer
Can someone help me add a wave to my Spawner script!!! 0 Answers
the floats wont be applied, Random.Range 1 Answer
Help With Dynamic Percentages 1 Answer
How to instantiate a platform each time another platform is 3 units away from the gamecontroller? 0 Answers