I am making a 3D infinite runner game in Unity in C#. When the player has reached the end of the tile it should spawn another tile and then delete the previous tile. When the player reached the end of the first tile it deletes that tile and spawns another(just like it should), but when the player reached the second tile is does nothing. Does someone have a solution?
Thanks
Here is my code: Old:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Terrain : MonoBehaviour
{
private List<GameObject> objs = new List<GameObject>();
public GameObject terrain;
public GameObject terrain2;
public GameObject player;
//private float z = 4130.875f;
private float safeZone = 260.0f;
private float tileLength = 260.0f;
private int animTilesCount = 2;
private Vector3 position;
void Start()
{
objs.Add(terrain);
objs.Add(terrain2);
for (int i = 0; i < animTilesCount; i++)
{
spawnTile();
}
}
void Update()
{
if ((objs.Count > 1) && (player.transform.position.z - objs[0].transform.position.z > safeZone))
{
spawnTile();
DeleteTile();
}
}
public void spawnTile()
{
position = objs[objs.Count - 1].transform.position;
position.z += tileLength; //21, -13
position.x += 21;
position.y += -13;
GameObject go = Instantiate<GameObject>(
terrain,
position,
terrain.transform.rotation);
go.transform.SetParent(transform);
objs.Add(go);
}
public void DeleteTile()
{
Destroy(objs[0]);
objs.RemoveAt(0);
}
}
New:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Terrain : MonoBehaviour
{
[SerializeField]
private List<GameObject> objs = new List<GameObject>();
public GameObject terrainPrefab;
public GameObject player;
public GameObject terrain;
public GameObject terrain2;
//private float z = 4130.875f;
private float safeZone = 260.0f;
private float tileLength = 260.0f;
private int animTilesCount = 2;
private Vector3 position;
void Start()
{
objs.Add(terrain);
objs.Add(terrain2);
for (int i = 0; i < animTilesCount; i++)
{
spawnTile();
}
}
void Update()
{
if ((objs.Count > 1) && (player.transform.position.z - objs[0].transform.position.z > safeZone))
{
Debug.Log("Hello");
spawnTile();
DeleteTile();
}
}
public void spawnTile()
{
position = objs[objs.Count - 1].transform.position;
position.z += tileLength; //21, -13
position.x += 21;
position.y += -13;
GameObject go = Instantiate<GameObject>(
terrainPrefab,
position,
terrainPrefab.transform.rotation);
go.transform.SetParent(transform);
objs.Add(go);
}
public void DeleteTile()
{
Destroy(objs[0]);
objs.RemoveAt(0);
}
}
terrain
andterrain2
variables? Starting with just a single terrain already inobj
will work, since you're adding more in youranimTilesCount
loop anyway. \$\endgroup\$