I'm trying to spawn infinite tiles in a 3D runner game, but the tiles are spawning at the wrong position and on the wrong axis.
Technically, the code is working as it should, it is spawning and deleting tiles, but it is doing so on the wrong axis: local z, instead of global z.
using System.Collections.Generic;
using UnityEngine;
public class TileSpawn: MonoBehaviour
{
public GameObject[] tilePrefabs;
public float zSpawn = 0;
public float tileLength = 20;
public int noOfTiles = 4;
public Transform plyTrns;
private List<GameObject> activeTiles = new List<GameObject>();
void Start()
{
for(int i = 0; i < noOfTiles; i++)
{
if (i == 0)
SpawnTile(0);
else
SpawnTile(Random.Range(0, tilePrefabs.Length));
}
}
void Update()
{
if(plyTrns.position.z -25 > zSpawn -(noOfTiles * tileLength))
{
SpawnTile(Random.Range(0, tilePrefabs.Length));
DeleteTile();
}
}
public void SpawnTile(int tileIndex)
{
GameObject go = Instantiate(tilePrefabs[tileIndex], transform.forward * zSpawn, transform.rotation);
activeTiles.Add(go);
zSpawn += tileLength;
}
private void DeleteTile()
{
Destroy(activeTiles[0]);
activeTiles.RemoveAt(0);
}
}