0
\$\begingroup\$

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);
}
}

enter image description here

\$\endgroup\$

1 Answer 1

0
\$\begingroup\$
GameObject go = Instantiate(tilePrefabs[tileIndex], transform.forward * zSpawn, transform.rotation);

transform.forward is "this object's local z direction".

If you want the global z direction, use Vector3.forward instead, or construct your vector directly:

var spawnPosition = new Vector3(0, 0, zSpawn); // = Vector3.forward * zSpawn
var go = Instantiate(tilePrefabs[tileIndex], spawnPosition, transform.rotation);
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .