Need help with an Endless Runner Game

Hi Guys,

So I’m trying to create an endless runner game. I have been following this tutorial here. Everything is sort of working, however no matter what I do I can’t get the ones at the back to delete. This is the code here. If anyone has any idea why this might not be working please let me know. My bridges are a little bigger than his also.

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class TileManager : MonoBehaviour {

public GameObject[ ] tilePrefabs;

private Transform playerTransform;
private float spawnZ = -6.0f;
private float tileLength = 350.0f;
private int amnTilesOnScreen = 7;
//privatefloatsafeZone=15.0f;

private List activeTiles;

//Usethisfor initialization
private void Start () {

activeTiles = new List();

playerTransform = GameObject.FindGameObjectWithTag (“Player”).transform;

for (int i = 1; i < amnTilesOnScreen; i++)
{
SpawnTile ();
DeleteTile ();

}
}

//Updateiscalledonceper frame
private void Update () {

if (playerTransform.position.z > (spawnZ - amnTilesOnScreen * tileLength))
{
SpawnTile ();

}
}

private void SpawnTile(int prefabIndex = -1)
{
GameObject go;
go = Instantiate (tilePrefabs [0]) as GameObject;
go.transform.SetParent (transform);
go.transform.position = Vector3.forward * spawnZ;
spawnZ += tileLength;
activeTiles.Add (go);
}

private void DeleteTile()
{
Destroy (activeTiles [0]);
activeTiles.RemoveAt (0);
}
}

Thanks.

So there is a lot to unpack here. Looking at your start method, specifically the for loop:

for (int i = 1; i < amnTilesOnScreen; i++)
{
    SpawnTile ();
    DeleteTile ();
}

First: you are starting at 1 and going until i is less that amnTilesOnScreen, which will not give you the total number of tiles you are expecting.
Second: you are calling SpawnTile() and DeleteTile() here, which right off the bat seems suspect. If the idea here is to pre-load the track with some number of tiles, then you don’t want to also be deleting tiles. Lets remove that call, giving us a new for loop like this:

for (int i = 0; i < amnTilesOnScreen; i++)
{
    SpawnTile ();
}

Next, look at your update. You have:

private void Update () {
  if (playerTransform.position.z > (spawnZ - amnTilesOnScreen * tileLength))
  {
    SpawnTile ();
  }
}

This is not removing the back tile, because you aren’t calling DeleteTile() here. Try adding it inside of your if statement, so you are removing a tile every time you add one:

private void Update () {
  if (playerTransform.position.z > (spawnZ - amnTilesOnScreen * tileLength))
  {
    SpawnTile ();
    DeleteTile ();
  }
}

I would start with these changes and see what that does for you. Without more information about how the game is behaving in a manner contrary to your expectations, I cannot provide further help.