Hey all, I have the following script that will create grid based terrain around the player. The problem is that it is creating it over and over. I want to add a check to see if there is already a block at that grid and if so, dont create a new block. I would also like to make it so old blocks are removed as the player moves away. Thanks for any help. Code (CSharp): using UnityEngine; using System.Collections; using System.Collections.Generic; using Random = UnityEngine.Random; public class tileGenerator : MonoBehaviour { public int xTerrain; public int zTerrain; public float scale; public float resolution; private Transform boardHolder; public GameObject[] ground; public GameObject[] water; // Use this for initialization void Update () { GameObject player = GameObject.Find ("Player"); //Find the players x and z location. int playerX = (int)player.transform.position.x; int playerZ = (int)player.transform.position.z; //Holds the gnerated tiles in a heading called board. boardHolder = new GameObject ("Board").transform; //For each square in range instantiate a prefab at that point, using the perlin noise as a highmap. for (int x = playerX -xTerrain; x< playerX + xTerrain; x++) { for (int z = playerZ-zTerrain; z< playerZ + zTerrain; z++) { float xCoord = x / resolution; float zCoord = z / resolution; //Generate a hightmap float height = Mathf.PerlinNoise (xCoord, zCoord); if (height < 0.6) { //Randomly pick a tile from the array to generate. GameObject toInstantiate = water [Random.Range (0, water.Length)]; //Generate it GameObject instance = Instantiate (toInstantiate, new Vector3 (x, 0, z), Quaternion.identity) as GameObject; instance.transform.SetParent (boardHolder); } if (height > 0.6) { // Randomly pick a tile from the array to generate. GameObject toInstantiate = ground [Random.Range (0, ground.Length)]; //Generate it GameObject instance = Instantiate (toInstantiate, new Vector3 (x, 0, z), Quaternion.identity) as GameObject; instance.transform.SetParent (boardHolder); } } } } } And what I am creating so far: Like I said though, I need it to only instantiate if a block isnt already there. Thanks!
Use a 2-dimensional array to keep track of your terrain tiles. You could make it be of Type GameObject[,] and assign the previously instantiated tile to the xy position, and check if a xy position is null or not if you want to find out if you need to instantiate something there. You could also make it be of Type int[,] and set the integer at a xy position to 0 if no tile is there, and 1 if it is. These are just example, but for all these kinds of tile or voxel terrain, it's common to have a 2- or 3-dimensional array for each tile/voxel that can be accessed at any time.
Yea I figured it out. Basically added a bool then when I created it turned it to true. Added a check before creating if block was already there.