- Home /
2D Efficient Realtime Terrain Generation
I have some working Terrain Generation code... the only problem is that it lags ALOT... Is there any way to optimize it more for a Top Down 2D Game?
The code is on the camera object
public void Update () {
this.transform.Translate (Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"), 0);
if (pos == this.transform.position) {
return;
}
Debug.Log ("Checking...");
pos = this.transform.position;
int xPos = Mathf.RoundToInt (this.transform.position.x);
int yPos = Mathf.RoundToInt (this.transform.position.y);
int xLow = xPos - 9;
int xHigh = xPos + 10;
int yLow = yPos - 5;
int yHigh = yPos + 6;
for (int x = xLow; x < xHigh; x++) {
for (int y = yLow; y < yHigh; y++) {
//Create TileInfo
bool isTaken = false;
foreach (Tile go in GameObject.FindObjectsOfType<Tile>()) {
if (go.pos == new Vector2 (x, y)) {
isTaken = true;
}
}
if (isTaken) {
continue;
}
TileInfo tile = new TileInfo ();
tile.tileSprite = sprites [0];
tile.isWalkable = true;
if (Mathf.PerlinNoise ((x + 0f) / 1, (y + 0f) / 1) >= 0.9f) {
tile.isWalkable = false;
tile.tileSprite = sprites [1];
}
GameObject newObject = (GameObject)Instantiate (spriteObject, new Vector3 (x, y, 0), Quaternion.identity);
newObject.GetComponent<SpriteRenderer> ().sprite = tile.tileSprite;
newObject.GetComponent<Tile> ().pos = new Vector2 (x, y);
}
}
}
It's a common mistake to instantiate seperate GameObjects for each tile. Unity can't handle the amount of GameObjects and instantiating is also very resource-intensive. Ins$$anonymous$$d, keep your tile information stored in a 2D array and generate your mesh by code, divided into chunks if neccessary. There are lots of tutorials, sample scripts and assets available for procedural mesh generation.
Your answer
![](https://koobas.hobune.stream/wayback/20220612103225im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How can i use perlin noise to create better world? 0 Answers
Terrain help 0 Answers
Perlin Noise for 3d Voxel Terrain 1 Answer
[C#] Wondering what is amiss with my 1D Perlin Noise Terrain Generator? 2 Answers
Can anyone explain this code? 1 Answer