Skip to content

Instantly share code, notes, and snippets.

@benthroop
Created July 18, 2024 12:06
Show Gist options
  • Save benthroop/759cf90b92f3f18412372561cf512879 to your computer and use it in GitHub Desktop.
Save benthroop/759cf90b92f3f18412372561cf512879 to your computer and use it in GitHub Desktop.
Function to make a new TerrainData and assign it to a selected Terrain GameObject.
//Two editor functions you can put wherever you like
public void CreateTerrainData()
{
//get the selected terrain gameobject
//create a terrain asset in the folder selected in the project view
//name the terrain data the same as the gameobject
//assign the terraindata to the terrain and the terraincollider
var t = Selection.activeGameObject.GetComponent<Terrain>();
if (t == null)
{
Debug.LogError("No terrain component on selected object. Aborting.");
return;
}
var tcol = t.gameObject.GetComponent<TerrainCollider>();
if (tcol == null)
{
Debug.LogError("No terrain collider on selected object. Aborting.");
return;
}
var tgoName = t.gameObject.name;
TerrainData terrainData = new TerrainData ();
const int size = 513;
terrainData.heightmapResolution = size;
terrainData.size = new Vector3 (2000, 600, 2000);
terrainData.heightmapResolution = 512;
terrainData.baseMapResolution = 1024;
terrainData.SetDetailResolution(1024, terrainData.detailResolutionPerPatch);
var selectedProjectPath = GetSelectedPathOrFallback();
AssetDatabase.CreateAsset(terrainData, selectedProjectPath + tgoName + "_terrainData.asset");
t.terrainData = terrainData;
tcol.terrainData = terrainData;
}
public string GetSelectedPathOrFallback()
{
string path = "Assets";
foreach (UnityEngine.Object obj in Selection.GetFiltered(typeof(UnityEngine.Object), SelectionMode.Assets))
{
path = AssetDatabase.GetAssetPath(obj);
if (!string.IsNullOrEmpty(path) && File.Exists(path))
{
path = Path.GetDirectoryName(path);
break;
}
}
return path + "/";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment