Search Unity

Modifying terrain at runtime LAGS

Discussion in 'Scripting' started by JohnParask, Feb 27, 2015.

  1. JohnParask

    JohnParask

    Joined:
    Jul 7, 2014
    Posts:
    323
    Hey guys, i'm trying to modify the terrain at runtime by using the build-in SetHeights function. It works perfect but it drops the FPS from 70-90 to 2-3 even if i try to modify 1 point. I tried at very small terrains and at normal terrains, there was no difference.

    Here is the script i'm using :

    Code (CSharp):
    1.  public Terrain currentTerrain;
    2.  
    3.     int xRes;
    4.     int zRes;
    5.     float[,] heights;
    6.     TerrainData tData;
    7.  
    8.     void Start()
    9.     {
    10.         tData = currentTerrain.terrainData;
    11.         xRes = tData.heightmapWidth;
    12.         zRes = tData.heightmapHeight;
    13.         heights = tData.GetHeights(0, 0, xRes, zRes);
    14.     }
    15.  
    16. void Update()
    17.     {
    18.         if (Input.GetKeyDown(KeyCode.Mouse0))
    19.         {
    20.             RaycastHit hit;
    21.             Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    22.             if (Physics.Raycast(ray, out hit))
    23.             {
    24.                 ModifyTerrain(hit.point);
    25.             }
    26.         }
    27. }
    28.  
    29. private void ModifyTerrain(Vector3 point)
    30.     {
    31.         int mouseX = (int)((point.x / tData.size.x) * xRes);
    32.         int mouseZ = (int)((point.z / tData.size.z) * zRes);
    33.  
    34.         float y = heights[mouseX, mouseZ];
    35.         float[,] modifiedHeights = new float[1, 1];
    36.         y += 0.005f;
    37.         for (int x = -6; x <= 6; x++)
    38.         {
    39.             for (int z = -6; z <= 6; z++)
    40.             {
    41.                 if ((mouseZ + z) <= tData.heightmapHeight)
    42.                 {
    43.                     modifiedHeights[0, 0] = y;
    44.                     heights[mouseX, mouseZ + z] = y;
    45.                     tData.SetHeights(mouseX + x, mouseZ + z, modifiedHeights);
    46.                 }
    47.             }
    48.         }
    So is there any way to prevent the lag or any other way to modify the terrain ?