How to place trees during runtime?

I’m trying to place trees during runtime but when I spawn them they can’t be seen visually. When I debug I can tell the trees are being added to the treeInstances array. The documentation doesn’t have any examples on how to actually do this but it appears to be pretty straightforward. If there is anyone who can point me in the right direction I would appreciate it. Btw this is how I’m trying to do this.

TreeInstance treeInstance = new TreeInstance();
treeInstance.prototypeIndex = 0;
Vector3 position = spawnPos;
position.y = terrain.terrainData.GetInterpolatedHeight(terrainX, terrainZ);
treeInstance.position = position;
terrain.AddTreeInstance(treeInstance);
terrain.Flush();
print(terrain.terrainData.treeInstances.Length); //does show trees are being added to the treeInstances array

Are you actually doing something with the trees after putting them in your array? I dont see any for loops or anything that are cycling through all of the instances in the array.

Problem is the TreeInstance class has more variables than just the prototypeIndex and the position. You need to assign values to all the variables (scale, colour, etc).

I can be wrong (never played with trees yet) … but perhaps you have to add treeInstance to terrain.terrainData.treeInstances instead of treeInstanceList.

Or you can use terrain.AddTreeInstance(treeInstance).

1 Like

I indeed didn’t check the scale and colour I sort of assumed they were optional but not mandatory to make it work, I will try it out.

Thanks for the tip Fraconte I actually did use terrain.AddTreeInstance that but I placed the wrong code here lol. I will change it right away.

I tried setting the heightscale/widthscale and color but this doesn’t make any difference. I already spent 3 days on this…

Ok I have found the problem after searching for a long time. Basically the position I assigned to the tree was incorrect so it didn’t spawn where I expected it. I didn’t realize a position on the terrain has a value between 0.0 and 1.0 because treeInstance.position just asks for a Vector3. All I had to do was just calculate (1.0f/terrainResolution) * terrainTileX.

2 Likes

Also note that heightscale and widthscale should be defined too as they take default value of 0 otherwise.