Can You help me Fix This? (Infinite level Generator)
I am making a game called Boxel Run 3D, and I am in process of making an infinite level gen. This is THE LAST THING I need to code to finish the game, but I could not fix it FOR 6 MONTHS. It kind of works, but when you are about to move from one tile to another, the tile disappears underneath your feet, and you die.
Here is my code:
using System.Collections; using System.Collections.Generic; using System.Net.NetworkInformation; using UnityEditor; using UnityEngine; using UnityEngine.PlayerLoop;
public class LevelController : MonoBehaviour { public LevelPiece[] levelPieces; public int DrawDistance; public float pieceLength; public Transform _camera; float currentcamStep; float lastcamStep; public float ttw = 1.0f; public float done = 0.0f; public float speed;
Queue<GameObject> activePieces = new Queue<GameObject>();
List<int> probabilityList = new List<int>();
private void Start() {
BuildProbabilityList();
for (int i = 0; i < DrawDistance; i++) {
SpawnNewPieces();
}
currentcamStep = (int)((_camera.transform.position.z + 3.15) / pieceLength);
lastcamStep = currentcamStep;
}
private void Update() {
_camera.transform.position = Vector3.MoveTowards(_camera.transform.position, _camera.transform.position + Vector3.forward, Time.deltaTime * speed);
currentcamStep = (int)(_camera.transform.position.z / pieceLength);
if (currentcamStep != lastcamStep) {
DespawnPiece();
lastcamStep = currentcamStep;
SpawnNewPieces();
}
}
void SpawnNewPieces() {
int pieceIndex = probabilityList[UnityEngine.Random.Range(0, probabilityList.Count)];
GameObject newLevelPiece = Instantiate(levelPieces[pieceIndex].prefab, new Vector3(0f, 0f, pieceLength * (currentcamStep + activePieces.Count) * pieceLength), Quaternion.identity);
activePieces.Enqueue(newLevelPiece);
}
void DespawnPiece() {
//wait for seconds?
GameObject oldLevelPiece = activePieces.Dequeue();
Destroy(oldLevelPiece);
}
void BuildProbabilityList() {
int index = 0;
foreach (LevelPiece piece in levelPieces) {
for (int i = 0; i< piece.probability; i++) {
probabilityList.Add(index);
}
index++;
}
}
} [System.Serializable] public class LevelPiece { public string name; public GameObject prefab; public int probability = 1; }
Any Ideas? (Btw if you see random code it id for other things in my game :) )