In Unity, I'm trying to make a ground, which is the form of a matrix, procedurally generate as my player and camera move through the scene. Imagine a matrix adding a new line everytime the player gets close enough to the end of it.
I've got this ground on which the player's running. The ground is made of different square prefabs, equal in size. I'm using this code to randomly pick a prefab from a GameObject array and build a matrix out of them which represents my ground. Right now I'm generating the whole ground at runtime, but I want to make it so it infinitely generates new lines in the matrix as the player is progressing. I've tried multiplying a distance variable with my Instantiate transform position, making it look like this:
GameObject theTile = Instantiate(thePrefab, transform + transform.forward * distanceAhead);
I've also tried setting up an empty GameObject called SpawnPoint as a child of Camera which moves along with the Camera and my LevelInstancing moving a little everytime, and if it intersects the SpawnPoint, it should spawn another line of prefabs in that matrix, the code would've looked like this:
void CreateMap()
{
for (int row = 1; row <= myGrid.y; row++)
{
for (int col = 1; col <= myGrid.x; col++)
{
if(transform.position.z < spawnPoint.transform.position.z)
{
transform.position = new Vector3(transform.position.x, transform.position.y, transform.position.z + distance);
int n = Random.Range(0, prefabTiles.Length);
GameObject thePrefab = prefabTiles[n];
GameObject theTile = Instantiate(thePrefab, transform);
theTile.name = "Tile_" + col + "_" + row;
theTile.transform.localPosition = new Vector3((col - 1) * tileDimensions.x, 0, (row - 1) * tileDimensions.z);
mapList.Add(theTile);
}
}
}
}
But it doesn't work properly.
This is my working code I am using right now.
void Start()
{
CreateMap();
}
void CreateMap()
{
for (int row = 1; row <= myGrid.y; row++)
{
for (int col = 1; col <= myGrid.x; col++)
{
int n = Random.Range(0, prefabTiles.Length);
GameObject thePrefab = prefabTiles[n];
GameObject theTile = Instantiate(thePrefab, transform);
theTile.name = "Tile_" + col + "_" + row;
theTile.transform.localPosition = new Vector3((col - 1) * tileDimensions.x, 0, (row - 1) * tileDimensions.z);
mapList.Add(theTile);
}
}
}