Hello Unity Folks,
I am working on a game that will use some sort of object pooling/instantiating system. My goal is to create an endless track with my prefabs in the first image below. I want to choose a random prefab each time and splice it to my current track with correct position and rotation. It would seem like in the second image where i manually adjusted the positions and rotations of my prefabs(I created my prefabs in blender to be 60 unity units either in vertical or horizontal, meaning my positions are the multiples of 30).
It is somewhat easy to instantiate straight objects indefinetly but i have no idea how to involve different rotation and position everytime that will make my race track complete. Here is my simple script to instantiate straight prefabs indefinitely. What should i involve in SpawnTiles() method in order to achieve what i want. The answer does not have to be spesific. I can use some mind opener ideas.
Thanks up front for your help.
public GameObject[] tilePrefabs;
private Transform playerTransform;
private float spawnZ = 35.5f;
private float tileLength = 60.0f;
private float safeZone = 60;
private int lastPrefabIndex = 0;
private int amountTilesOnScreen = 3;
private List<GameObject> activeTiles;
void Start()
{
activeTiles = new List<GameObject>();
playerTransform = GameObject.FindGameObjectWithTag("Cars").transform;
for (int i = 0; i < amountTilesOnScreen; i++)
{
SpawnTiles();
}
}
void Update()
{
if (playerTransform.position.z - safeZone > (spawnZ - amountTilesOnScreen * tileLength))
{
SpawnTiles();
DeleteTile();
}
}
private void SpawnTiles(int prefabIndex = -1)
{
GameObject go = Instantiate(tilePrefabs[RandomPrefabIndex()]) 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);
}
private int RandomPrefabIndex()
{
if (tilePrefabs.Length <= 1)
{
return 0;
}
int randomIndex = lastPrefabIndex;
while (randomIndex == lastPrefabIndex)
{
randomIndex = Random.Range(0, tilePrefabs.Length);
}
lastPrefabIndex = randomIndex;
return randomIndex;
}