Accessing terrain settings through code

I’m trying to find a couple of terrain settings through code but have been unable to find anything that has worked yet. Here’s my list

  • _terraindata.SetHeight.height ( Unable to find a way to access the brush tool to use the SetHeight and flatten options )
  • Paint Texture → Create Layer ( So I can assign a base texture when I create my terrain )

My code so far

                //Create Terrain
                GameObject terrain = new GameObject();
                TerrainData _terraindata = new TerrainData();

                //Assign terrain settings
                _terraindata.heightmapResolution = 65;
                _terraindata.size = new Vector3(1000, 1800, 1000);

                //Apply settings to terrain
                terrain = Terrain.CreateTerrainGameObject(_terraindata);

setting heights:
with an array: Unity - Scripting API: TerrainData.SetHeights
with a rendertexture:
Unity - Scripting API: TerrainData.CopyActiveRenderTextureToHeightmap

painting textures:

and setting the terrain layers:

List <TerrainLayer> tl = new List <TerrainLayer>();
//the layer must be available in the Assets/Resources/ folder
tl.Add(Resources.Load<TerrainLayer>("TerrainLayer/Water"));
tl.Add(Resources.Load<TerrainLayer>("TerrainLayer/Grass"));
terrain.terrainData.terrainLayers = tl.ToArray();
3 Likes

Thanks for the help! Managed to get texture layers adding but have a slight issue with the heights still. Managed to get it working but it only applies the height to a corner of my terrain. Do i need a for loop for each part of my terrain? Or is there a way to apply it to the entire terrain?

                //Set terrain height
                float[,] heights = new float[65, 65];
                heights[x, y] = 0.25f; //Sets height
                _terraindata.SetHeights(0,0, heights);

each entry in the heights array corresponds to one point on the terrain. So in your code you will have all at zero except one at x,y which will be at 0.25.
You need to set all values of the array to the correct height.

If you want to change all heights of the complete terrain by the same value you could just change the transform of the gameObject. This would be a lot faster.