Convert Prototypes To Tree Game Objects

Dictionary<int, GameObject> ConvertPrototypesToTreeGameObjects(TerrainToMeshPrototype[] data, InstantiateGameObjectMethod instantiateGameObjectMethod, float exportPercentage, float yRotation = 360, float yRotationRandomize = 360, float followTerrainSurface = 0, bool followTerrainSurfaceRandomize = false)

Instantiates tree gameObjects based on the TerrainToMeshPrototype[] data.

Returned dictionary key is the tree index inside TerrainData.treePrototypes array and value holds parent gameObject containing instantiated tree prefabs with the same index.

//Example of exporting trees from TerrainData

//Exporting terrain mesh
Mesh terrainMesh = terrainData.TerrainToMesh().ExportMesh(100, 100);

//Creaing GameObject using terrain mesh
GameObject terrainGO = new GameObject("Terrain");
terrainGO.AddComponent<MeshFilter>().sharedMesh = terrainMesh;
terrainGO.AddComponent<MeshRenderer>().sharedMaterial = TerrainToMeshUtilities.GetDefaultMaterial();


//Exporting trees from TerrainData
TerrainToMeshPrototype[] treePrototypes = terrainData.TerrainToMesh().ExportPrototypes(TerrainToMeshEnum.Prototype.Tree);

//Instantiating 50% of tree prefabs as gameObjects
Dictionary<int, GameObject> treeGO = TerrainToMeshUtilities.ConvertPrototypesToTreeGameObjects(treePrototypes, null, 50);

//Attaching instantiated tree gameObjects to the terrainMesh
foreach (var item in treeGO)
{
    item.Value.transform.SetParent(terrainGO.transform);
}

instantiateGameObjectMethod - If set to null, for instantiating tree prefabs is used Unity's Instantiate method. In this case instanced gameObjects have no references to the prefab files. Null value can be used when exporting trees in run-time.

Inside editor can be used delegate to the custom prefab instantiation method and keep prefab references.

//Example of Editor script using UnityEditor.PrefabUtility.InstantiatePrefab delegate method for instantiating tree prefabs

static GameObject InstantiatePrefabMethod(GameObject gameObjectOrAsset)
{
    return (GameObject)PrefabUtility.InstantiatePrefab(gameObjectOrAsset);
}

void ExportTrees()
{
    //Exporting trees from TerrainData
    TerrainToMeshPrototype[] treePrototypes = terrainData.TerrainToMesh().ExportPrototypes(TerrainToMeshEnum.Prototype.Tree);
                
    //Instantiating tree prefab gameObjects using delegate
    Dictionary<int, GameObject> treeGO = TerrainToMeshUtilities.ConvertPrototypesToTreeGameObjects(treePrototypes, InstantiatePrefabMethod, 50);
}

Last updated