[SOLVED] How to modify a Terrain at runtime and get back to original Terrain on exit?

Hello,

I’m trying to rotate a terrain in runtime, then I want the terrain to get back to its original rotation when I quit the app.

I have basically this algorithm:

  • Copy (“clone”) the Terrain Data
  • Rotate that copy
  • When quitting, the copy is automatically destroyed, so the terrain should get back to its original data.

The following code implements this algorithm:

 using UnityEngine;
public class RotateTerrain : MonoBehaviour
{
     [SerializeField]
     private Terrain terrain;
     void Start()
     {
         WorkOnNewCopy();
         // Now we can safely modify our terrain... Can we?
         TerrainRotate(terrain, degrees: 90);
     }
     void WorkOnNewCopy()
     {
         TerrainData backup_terrainData = terrain.terrainData;
         backup_terrainData.name = terrain.terrainData.name + "_tmp";
         backup_terrainData = Instantiate(backup_terrainData);
         terrain.terrainData = backup_terrainData;
         terrain.GetComponent<TerrainCollider>().terrainData = backup_terrainData;
         terrain.Flush();
     }
     void TerrainRotate(Terrain terrain, float degrees)
     {
         // Super-secret code
     }
}

It’s almost working: when I quit the app (or editor), I find myself with a weird mix between the original terrain, and the modified terrain. Everything seems to be back, except the ground texture (splat map). I feel close to the solution!

Have you got an idea? Thanks in advance! :slight_smile:
(same thread as: How to modify a Terrain at runtime and get back to original Terrain on exit? - Questions & Answers - Unity Discussions)

I used this awesome script to safely clone my terrain: Helper to deep-copy a TerrainData object in Unity3D · GitHub
Just had to write this:

terrain.terrainData = TerrainDataCloner.Clone(terrain.terrainData);
terrain.GetComponent<TerrainCollider>().terrainData = terrain.terrainData; // Don't forget to update the TerrainCollider as well

After this, the rotation works perfectly, and it reverts back automatically when I quit.
Just what I wanted!

4 Likes

Yes that helper class is key for any true deep-copy of a terrain. Only correct and updated solution i’ve found.