Delete sections behind player

Hi! I’ve developed my 3D “endless runner” game but I can’t manage to delete the sections that remains behind the player while he is running in the game.

Here’s my code for randomly generate a section every 2 seconds:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

 public class GenerateLevel : MonoBehaviour
 {
     public GameObject[] section;
     public int zPos = 50;
     public bool creatingSection = false;
     public int secNum;
     
     void Update()
     {
         if (creatingSection == false)
         {
             creatingSection = true;
             StartCoroutine(GenerateSection());
         }
         
     }
 
     IEnumerator GenerateSection()
     {
         secNum=Random.Range(0,3);
         Instantiate(section[secNum], new Vector3(0,0,zPos), Quaternion.identity);
         zPos+=50;
         yield return new WaitForSeconds(2);
         creatingSection=false;
     }
 }

Thank you!

Hi, you need to somehow store the sections and compare them with the player position. Or I would prefer to make a separate class for Sections and in update check their positions against the player position. I have made a quick script for you. I didnt run it but the idea is like this.

public class GenerateLevel : MonoBehaviour
{
    public Player player; // Fill this in inspector with the player instance

    public Section[] sectionPrefabs;   // Here I would put all the section prefabs
    public int zPos = 50;
    // public bool creatingSection = false; // No need
    public int secNum;
    
    bool isLevelGenerationActive = true;    // Make this variable false when you would like to stop the generation

    void Start()
    {
        StartCoroutine(GenerateSection());
    }

    IEnumerator GenerateSection()
    {
      // Use while here since then you dont need to use Update with the creatingSection bool
      while(isLevelGenerationActive)
      {
          secNum=Random.Range(0,3);
          Section sectionInstance = Instantiate(sectionPrefabs[secNum], new Vector3(0,0,zPos), Quaternion.identity);
          sectionInstance.player = player;  
          zPos+=50;

          yield return new WaitForSeconds(2);
          // creatingSection=false; // No need
      }
    }
}

public class Section : MonoBehaviour
{
    public Player player;
    public float destroyDistanceBehindPlayer;

    void Update()
    {   
        if(player.transform.position.z > transform.position.z + destroyDistanceBehindPlayer)
        {
            Destroy(gameObject);
        }
    }
}