I have created a small procedurally generated level for my game.
I made a level generator with an array that stores level prefabs and places them one after the other in an endless loop. My problem is that if i add a second level prefab into the array in unity it doesn’t randomize them, it only places down piece from the top slot of the array and never any other piece. Is there something in this code that could be limiting me? I’m new to programming so i might be being a real noob.
Could it be something like my naming conventions for the level piece prefabs? There not really uniform.
Have added a SS as well.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class LevelGenerator : MonoBehaviour
{
// used to access this script from other scripts
public static LevelGenerator instance;
//all level pieces blueprints used to copy from
public List<LevelPiece> levelPrefabs = new List<LevelPiece>();
//starting point of the very first level piece
public Transform levelStartPoint;
//all level pieces that are currently in the level
public List<LevelPiece> pieces = new List<LevelPiece>();
void Awake()
{
instance = this; // Creates the instance of this script
}
void Start()
{
GenerateInitialPieces(); // on start generate initial pieces
}
public void GenerateInitialPieces() // generate pieces function
{
for (int i = 0; i < 2; i++) // if i is less than 2 execute code
{
AddPiece(); // run add piece function
}
}
public void AddPiece()
{
//pick the random number
int randomIndex = Random.Range(0, levelPrefabs.Count - 1);
//Instantiate copy of random level prefab and store it in piece variable
LevelPiece piece = (LevelPiece)Instantiate(levelPrefabs[randomIndex]);
piece.transform.SetParent(this.transform, false);
Vector3 spawnPosition = Vector3.zero;
//position
if (pieces.Count == 0)
{
//first piece
spawnPosition = levelStartPoint.position;
}
else
{
//take exit point from last piece as a spawn point to new piece
spawnPosition = pieces[pieces.Count - 1].exitPoint.position;
}
piece.transform.position = spawnPosition;
pieces.Add(piece);
}
public void RemoveOldestPiece() // remove old piece function
{
LevelPiece oldestPiece = pieces[0];
pieces.Remove(oldestPiece);
Destroy(oldestPiece.gameObject);
}
}
Thanks in advance.