I’m new to Unity and was wondering how to let a game object interact with individual terrain trees without looping over the entire TreeInstances array? I have a dense forest with quite a number of terrain trees and a game object which is moving through this forest. Now I’d like to modify properties (heightScale etc.) of terrain trees which are within a radius of this game object.
In order to only call those trees which are within a distance of the game object and not the whole array, I use an OverlapSphere with radius 10:
foreach (GameObject i in cubes)
Collider hitColliders = Physics.OverlapSphere(i.transform.position, 10);
foreach (Collider c in hitColliders)
The debug log returns 5 hits, which is probably composed of the terrain and four terrain trees.
This seems reasonable, however the reported positions of those collisions are the same for the four trees. So how can I distinguish trees? And how to use this information to modify properties of terrain trees hit by the OverlapSphere?
Thanks in advance!
The problem is I’m using terrain trees (for reasons of performance) and not object trees. For this reason, the name ‘terrain’ is returned for every hit. According to the Unity manual, tree instances painted in the inspector window of the terrain object are not game objects but structs (Unity - Scripting API: TreeInstance). I could manipulate the properties of those tree structs as follows:
public class unityanswers : MonoBehaviour
// Use this for initialization
// Update is called once per frame
for (int i = 0; i < Terrain.activeTerrain.terrainData.treeInstanceCount; i++)
//let trees grow
if (Terrain.activeTerrain.terrainData.treeInstances*.heightScale < 0.99f)*
TreeInstance tree = new TreeInstance();
tree = Terrain.activeTerrain.terrainData.treeInstances*;*
var treeheight = Terrain.activeTerrain.terrainData.treeInstances*.heightScale;*
var treewidth = Terrain.activeTerrain.terrainData.treeInstances*.widthScale;*
var r = 0.1f;
tree.heightScale = treeheight + (treeheight * r * (1 - treeheight / 1));
tree.widthScale = treewidth + (treewidth * r * (1 - treewidth / 1));
However, it should be possible somehow to just iterate over those terrain trees which are nearby a game object (cube). Otherwise updates are associated with large computational overhead.
P.S.: The cube list is just a number of cubes, which are randomly distributed in the forest. It’s a made up examle to test Unity’s capabilities.