Alright, Im working in Unity in C# and Ive created a few simple functions to spawn a series of platforms (game objects) indefinitely in accordance with the z position of the player. I delete the game objects once they are securely out of sight and called this update method every time player moves forward:
void spawnSectorGroup()
{
int i = numSectorsToSpawn; //get position of last sectors, when its exceeded by player then delete and spawn again
while (i >= 0) {
int j = Random.Range (0, sectors.Length);
spawnSector (gamePosition.position, sectors [j]);
i--;
}
}
void checkAndUpdateSectors()
{
//print ("Player pos"+playerPosition.position);
//print ("last sector"+gamePosition.position);
if (gamePosition.position.z - playerPosition.position.z <= 20) { //safe value ahead
print ("theyre almost there, spawn new group");
print (gamePosition.position.z - playerPosition.position.z);
spawnSectorGroup ();
}
//destroy past ones
GameObject[] objects = FindObjectsOfType(typeof(GameObject)) as GameObject[];
//GameObject[] objects = GameObject.FindGameObjectsWithTag("Block");
foreach (GameObject o in objects) {
if (o.gameObject.tag == "Block" || o.gameObject.tag == "Cage" || o.gameObject.tag == "Animal" || o.gameObject.tag == "Enemy") {
if (playerPosition.position.z - o.transform.position.z >= 100) { //safe aways back
print ("destroying past object");
print (o.transform.position);
Destroy (o.gameObject);
}
}
}
}
void spawnSector(Vector3 relativePosition,GameObject sector){
GameObject newSector = GameObject.Instantiate (sector, relativePosition, transform.rotation) as GameObject;
gamePosition.position += newSector.GetComponent<Sector> ().length;
}
This all works, however Im worried in the long run if this spawning of about 10 new "sectors" each time the player is within 20 or so units of the last spawned sector will build up and create a lag from the multitude of game objects.
Im not experienced with indefinite spawning - will this be a problem? Or is this good practice with indefinite spawning?