unity3d – Unity C# script

I’m trying to make an endless game with Unity, I’m having a trouble thinking up a solution to make a necessary code to be programmed in my game. The player would continuously run forward just like “Temple Run” and “Subway Surfer” but I’m having trouble trying to spawning new tile and destroying the one behind the player after the player have ran out of the area for more than 2 seconds. Here’s my code (Or maybe I’m having trouble with the Ground not detecting the player itself so it doesn’t register it to be respawning/destroying)

public GameObject groundTile;
Vector3 nextSpawnPoint;

public void SpawnTile()
{
    GameObject temp = Instantiate(groundTile, nextSpawnPoint, Quaternion.identity);
    nextSpawnPoint = temp.transform.GetChild(1).transform.position;
}


void Start()
{
    for (int i = 0; i < 20; i++)
    {
        SpawnTile();
    }
}

And another one for the GroundTile

GroundSpawner groundSpawner;

void Start()
{
    groundSpawner = GameObject.FindObjectOfType<GroundSpawner>();
}

private void OnTriggetExit (Collider other)
{
    groundSpawner.SpawnTile();
    Destroy(gameObject, 2);
}

Read more here: Source link