Hey guys, I’ve been using a script that allows me to chop down terrain trees and replacing them with falling prefabs. the only problem is, when i chop the tree, on the next run of the application the trees don’t come back. Can someone send me some example, or tell me how I can do that?
Here’s my code for replacing trees with prefabs:
private void Start()
{
TreeInstances = new List<TreeInstance>(Terrain.activeTerrain.terrainData.treeInstances);
Debug.Log("Tree Instances:" + TreeInstances.Count);
}
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
Debug.Log("Hitted !");
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, 10.0f))
{
if (hit.collider.name != Terrain.activeTerrain.name)
{
return;
}
?
float sampleHeight = Terrain.activeTerrain.SampleHeight(hit.point);
if (hit.point.y <= sampleHeight + 0.01f)
{
return;
}
TerrainData terrain = Terrain.activeTerrain.terrainData;
TreeInstance[] treeInstances = terrain.treeInstances;
float maxDistance = float.MaxValue;
Vector3 closestTreePosition = new Vector3();
int closestTreeIndex = 0;
for (int i = 0; i < treeInstances.Length; i++)
{
TreeInstance currentTree = treeInstances[i];
Vector3 currentTreeWorldPosition = Vector3.Scale(currentTree.position, terrain.size) + Terrain.activeTerrain.transform.position;
float distance = Vector3.Distance(currentTreeWorldPosition, hit.point);
if (distance < maxDistance)
{
maxDistance = distance;
closestTreeIndex = i;
closestTreePosition = currentTreeWorldPosition;
}
}
TreeInstances.RemoveAt(closestTreeIndex);
terrain.treeInstances = TreeInstances.ToArray();
float[,] heights = terrain.GetHeights(0, 0, 0, 0);
terrain.SetHeights(0, 0, heights);
Instantiate(FallingTreePrefab, closestTreePosition, Quaternion.identity);
Debug.Log("Tree was destroyed");
}
}
}