The tree prefabs and tree instances are two different things entirely.
For each type of tree you want, you need a tree prefab - one per type. Usually you can (and should) set this up in the editor not at runtime. If you need to generate the terrain 100% from scratch you still can though, just by replacing this array with a new array of prefab references:
After you adjust that array, make sure you run yourTerrain.terrainData.RefreshPrototypes();
Now your terrain has the prototype(s) you want to spawn, time to actually to about adding the tree instances (the individual trees).
public void SpawnTree(Vector3 position){
if (MapTerrain.terrainData.treePrototypes.Length > 0){
TreeInstance newInstance = new TreeInstance();
newInstance.position = WorldToTerrainPoint(position);
newInstance.heightScale = 0.3f;
newInstance.widthScale = 0.3f;
newInstance.prototypeIndex = 0;
newInstance.lightmapColor = Color.white;
newInstance.color = Color.white;
MapTerrain.AddTreeInstance(newInstance);
MapTerrain.Flush();
}
}
TreeInstance newInstance = new TreeInstance();
newInstance.position = new Vector3(wherever you want it);
newInstance.heightScale = 1; newInstance.widthScale = 1;
newInstance.prototypeIndex = whatever index you want (if you only have 1 prototype, just set this to zero)
newInstance.lightmapColor = Color.white; If you don't set the lightMap color your trees will appear as black silhouettes
newInstance.lightmapColor = Color.white;
YourTerrain.AddTreeInstance(newInstance);
MapTerrain.Flush();
If you are generating a lot of trees, I suggest making your own TreeInstance[ ] - populating that - and replacing the YourTerrain.terrainData.treeInstances variable with your own array instead of pushing each individual tree (for performance reasons).
NOTE:
The location of your trees is based on a float from 0 to 1, it is NOT a world position. (so 0,0 = bottom right corner of the terrain, 1,1 = top left, or vice versa - don’t remember off the top of my head).
For the heights yea, SetHeight() is the ticket there. I STRONGLY recommend using SetHeights though and setting the entire hightmap in a single call, as the performance impact of calling SetHeight for every pixel in the heightmap is huge.
EDIT:
/facepalm - sorry, didn’t realize this thread was a necro.
@Furfire - yea, you want SetHeight/SetHeights (the same advice applies, do it all in a single call if you can - much faster). You may need to call YourTerrain.Flush() after you do this to see the changes, not sure if the heightmap requires a flush or not off the top of my head.