Continuois 2d terrain generator

Hi there people! I’m trying to do a continuous game world with this script. The idea it’s that when the player its in a plataform, unity create 2 other more, one to the left and one to the right, and when the player go to other plataform, delete and recreate. This is my script but, the game create infint clones and then crash. Can you help me ? Thanks !

using System.Collections;

public class CreacionPlaneta2 : MonoBehaviour 
{
	public int alguienEstaPisandome = 0;
	public int mePisaron = 0;
	public int creoYBorro = 0;
	public GameObject nuevoPlaneta1;
	public GameObject nuevoPlaneta2;
	public Vector3 nuevaPosicion1;
	public Vector3 nuevaPosicion2;
	public GameObject[] arregloPlaneta = new GameObject[3];
		
	public string mePisaronS = "nil";
	public string alguienEstaPisandomeS = "nil";
	public string creoYBorros = "nil";
	public string ii = "nil";


	void Start () 
	{
		
	}

	void Update () 
	{
		
		if(this.mePisaron >= 1)
		{
			this.mePisaronS = "1";
			if(this.alguienEstaPisandome > 0)
			{
				alguienEstaPisandomeS = this.creoYBorro.ToString();
				if(this.creoYBorro == 0)
				{
					creoYBorros = this.creoYBorro.ToString();
					this.arregloPlaneta[1] = this.gameObject;
					borrarOtrosMundos();
					crearNuevosMundos();
					this.creoYBorro += 1;
				}
			}
		}
	}


	//Duplica el mapa del lado que esta el jugador
	void crearNuevosMundos()
	{
		ii = "NuevosMundos";

 		//Creo para la izquierda
		this.nuevaPosicion1.x = (this.transform.position.x - (tamanioMapa/2));
		this.nuevoPlaneta1 = (GameObject)Instantiate( this.gameObject, nuevaPosicion1, transform.rotation);
		this.arregloPlaneta[0] = this.nuevoPlaneta1;
		//Creo para la derecha
		this.nuevaPosicion2.x = (this.transform.position.x + (tamanioMapa/2));
		this.nuevoPlaneta2 = (GameObject)Instantiate( this.gameObject, nuevaPosicion2, transform.rotation);
		this.arregloPlaneta[2] = this.nuevoPlaneta2;
	}
	//------------------------------
	
	//Borra el mapa del lado que no esta el jugador
	void borrarOtrosMundos()
	{
		Destroy(this.arregloPlaneta[0]);
		Destroy(this.arregloPlaneta[2]);
	}
	//------------------------------

	//Chequea si esta tocando algo
	public void OnCollisionEnter(Collision collision)
	{
		this.alguienEstaPisandome += 1;
		this.mePisaron += 1;
	}
	
	public void OnCollisionExit(Collision collision)
	{
		this.alguienEstaPisandome -= 1;
	}
	//------------------------------
}

If I had to guess I would say you’re getting more OnCollisionEnter/OnCollsionExit calls than you assume.

I would simplify things by doing it this way:

  1. Generate enough platforms at start to fill the screen.
  2. When you move past a certain distance in either direction move the farthest left platform to the far right (and vice versa).

Generating/destroying game objects constantly is bad for performance anyway. The “Unity” way is to keep a constant number of objects in the scene and move them around as needed.