0
\$\begingroup\$

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;
    }
}

SEE THE TERRAIN KEEPS SPAWNING AND SPAWNING

\$\endgroup\$
  • 1
    \$\begingroup\$ Take a look at this tutorial by Sebastian League. Procedural Terrain Generation is a pretty complicated process but this guy does a very good job explaining it. Link is Here \$\endgroup\$ – Dtb49 May 21 '18 at 18:10
1
\$\begingroup\$

If the player isn’t looking at a tile then it does not need to be there, so we can use that memory for something else. Instead of creating a new tile every single time, you should create a fixed number of tiles ahead of time and move ones that are not visible into view as if they were new ones, essentially recycling the tile.

This technique is called “Object Pooling”. I’m not super familiar with Unity but a search for “Unity Object Pooling” brings up some reasonable looking resources about the subject.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.