- Home /
Can terrain trees run their own script?
I've got a terrain covered in trees. The tree prefab has a script on it that doesn't run for the terrain instantiated trees. Is it not possible to run scripts on terrain trees?
Answer by BastianUrbach · Jan 26, 2020 at 11:32 AM
Not quite since Terrain trees are not regular GameObjects but you can do something similar by putting a script on the terrain itself that calls some method for each tree instance on the terrain.
TreeInstance[] trees;
void Start() {
var terrain = GetComponent<Terrain>();
trees = terrain.terrainData.treeInstances;
foreach (var tree in trees) {
...
}
}
void Update() {
foreach (var tree in trees) {
...
}
}
@BastianUrbach How would I do this if I have 3 types of trees but only need to add a certain line of code to 1 of the 3? Please please help! It would save me hours of work!
@BastianUrbach How would I do this if I have 3 types of trees but only need to add a certain line of code to 1 of the 3? Please please help! It would save me hours of work!
First you need to figure out which index the tree prototype has. This is simply its position in the terrain component inspector. If it's the first tree type you added to the terrain, the prototype index is 0, if it's the second one, the prototype index is 1 and so on. Then just add this to the two foreach loops:
if (tree.prototypeIndex == yourPrototypeIndex) {
// put code here
}
Alternatively you could also filter the 'trees' array just once in Start, e.g. using Linq:
using System.Linq;
...
trees = terrain.terrainData.treeInstances;
trees = trees.Where(
t => t.prototypeIndex == yourPrototypeIndex
).ToArray();
Your answer
Follow this Question
Related Questions
Terrain tree is not working 1 Answer
Paint trees with scripts? 1 Answer
Unity terrain trees on layers 1 Answer
How to make terrain trees receive shadow 2 Answers
Tree Creator Problems 1 Answer