- Home /
Question by
erran liu · Aug 20, 2013 at 08:14 AM ·
collisionterraincollider
How to know the tree's type on terrain I am colliding?
When I collide with the trees painted on terrain, I can only get the terrain's information from the CollideListener.
I want to make the collision behaviour different on different tree types, anyone have any idea?
Comment
Answer by Linus · Aug 20, 2013 at 09:10 AM
There may be a way to get the closest tree at the location you are standing. But I dont think you can get the colliding tree from the terrain tree collider it self.
I was working on finding tree positions yesterday. So here is a script that will place a normal collider at all tree positions. And then inform a script of the type of tree that is standing there.
treeInstance does not have a name, but you can get the index number of the tree type.
addTreeColliders.js
#pragma strict
/*
You will need to assign a prefab with the script treeInfo.js and basic trigger collider
*/
var treeColliderPrefab : GameObject;
function Start() {
var pos : Vector3;
var treeCollider : GameObject;
for (var i=0; i < Terrain.activeTerrain.terrainData.treeInstances.Length; i++){
pos = Vector3.Scale(Terrain.activeTerrain.terrainData.treeInstances[i].position,Terrain.activeTerrain.terrainData.size)+ Terrain.activeTerrain.transform.position;
Debug.Log('A tree at world position '+pos+' type: '+ Terrain.activeTerrain.terrainData.treeInstances[i].prototypeIndex);
treeCollider = Instantiate(treeColliderPrefab, pos, Quaternion.identity);
treeCollider.GetComponent(treeInfo).treeType = Terrain.activeTerrain.terrainData.treeInstances[i].prototypeIndex;
//You might want to parent all colliders to something so they dont clutter the scene
//treeCollider.transform.parent = //sometransform
}
}
treeInfo.js
#pragma strict
var treeType : int; //Couolp be used to lookup a static array of tree types
function OnTriggerEnter(col : Collider){
Debug.LogError('The tree here is of type '+treeType);
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613112558im_/https://answers.unity.com/themes/thub/images/avi.jpg)