I am making a game in Unity 5 in C# and I need to make the terrain infinite. I have tried to make it infinite but it just keeps spawning the terrain too much times and then the game crashes. Does someone know how I can make the terrain infinite? Here is my code.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TerrainScript : MonoBehaviour
{
public Transform PlayerTransform;
private float SpawnZ = 4139f;
public GameObject[] prefabs;
private float RoadLength = 2.2f;
private int amountRoads = 6;
private List<GameObject> roadList;
public void Start()
{
roadList = new List<GameObject>();
}
public void Update()
{
if(PlayerTransform.position.z > (SpawnZ - amountRoads * RoadLength))
{
spawnTile(0);
}
}
public void spawnTile(int index)
{
GameObject go;
go = Instantiate(prefabs[index]) as GameObject;
go.transform.SetParent(transform);
go.transform.position = Vector3.forward * SpawnZ;
SpawnZ += RoadLength;
}
}