Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Terrain not having different terraindatas

Discussion in 'Scripting' started by FrostKnightTheGreat, Jul 7, 2023.

  1. FrostKnightTheGreat

    FrostKnightTheGreat

    Joined:
    Aug 22, 2020
    Posts:
    9
    I have a problem I need help with, I am trying to instantiate multiple terrain objects through script. Then I am trying to create a new terrain asset through another script which will control the random terrain's properties, however, all of the terrains are sharing the same terrain properties even though they must technically have different terrain properties. How do I create terrain data assets dynamically? Pls help with this, thank you.

    public int width = 64;
    public int length = 64;
    public float heightScale = 20f;
    public float maxHeight = 10f;
    private Terrain terrain;
    private void Start()
    {
    GenerateRandomTerrain();
    }
    private void GenerateRandomTerrain()
    {
    TerrainData terrainData = new TerrainData();
    terrainData.heightmapResolution = width + 1;
    int heightmapWidth = terrainData.heightmapResolution;
    int heightmapHeight = terrainData.heightmapResolution;
    float[,] heights = new float[heightmapWidth, heightmapHeight];
    for (int y = 0; y < heightmapHeight; y++)
    {
    for (int x = 0; x < heightmapWidth; x++)
    {
    float height = Mathf.PerlinNoise(x / (float)width * heightScale, y / (float)length * heightScale) * maxHeight;
    heights[x, y] = height / maxHeight;
    }
    }
    terrainData.SetHeights(0, 0, heights);
    Vector3 terrainSize = terrainData.size;
    terrainSize.x = width;
    terrainSize.z = length;
    terrainData.size = terrainSize;
    terrain.terrainData = terrainData;
    }

    this is the terrain code.
     
    Last edited: Jul 7, 2023
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,563
    If you post a code snippet, ALWAYS USE CODE TAGS:

    How to use code tags: https://forum.unity.com/threads/using-code-tags-properly.143875/

    The steps to clone TerrainData is simply to Instantiate<T>() a fresh copy of it and reassign it to your Terrain, and possibly your TerrainCollider if you want.

    Code (csharp):
    1. TerrainData terrainData = Instantiate<TerrainData>( terrain.terrainData);
    2.  
    3. // TODO: change your terrainData here...
    4.  
    5. terrain.terrainData = terrainData;
    Here's another example of manipulating TerrainData:

     
  3. FrostKnightTheGreat

    FrostKnightTheGreat

    Joined:
    Aug 22, 2020
    Posts:
    9
    Thanks for helping but the problem still persists all of the terrain objects have the same terrain
    upload_2023-7-7_20-21-28.png All these terrain look the same