Programatically placed trees end up in a wrong place

I am working on a terrain generator, I got my terrain going, so I decided to play around with trees.

I add 5 tree prototypes to the terrain data like so:

		List< TreePrototype > treePrototypes = new List< TreePrototype >();
		foreach ( GameObject treePrefab in this.treePrefabs )
			TreePrototype treePrototype = new TreePrototype();
			treePrototype.prefab = treePrefab;
			treePrototypes.Add ( treePrototype );
		terrainData.treePrototypes = treePrototypes.ToArray();

Then, I have an array of points that are within the terrain and I would like to place trees in those locations. I try to do so using:

		foreach ( Vector3 point in spawnPoints )
			Vector3 onTerrainPosition = point;
			RaycastHit hit;
			if ( Physics.Raycast( point, -Vector3.up, out hit ) )
				if ( == "Terrain" )
					onTerrainPosition = hit.point;

			TreeInstance newTree = new TreeInstance();
			newTree.position = onTerrainPosition;
			newTree.widthScale = 1;
			newTree.heightScale = 1;
			newTree.color = Color.yellow;
			newTree.lightmapColor = Color.yellow;
			newTree.prototypeIndex = Random.Range ( 0, terrainData.treePrototypes.Length );
			Terrain.activeTerrain.AddTreeInstance( newTree );

All this works, except that all the trees are at “Tree Instance at (1.0, 0.0, 1.0)”.

I thought maybe it’s because terrain hasn’t been placed in the scene yet, but I delayed the tree placement call and get the same result.

If during run time I click on “Mass Place Trees” everything works - I get tons of trees all over the place.

What could cause the positions to be off/reset/wrong? Maybe those locations don’t have enough space? Any thoughts?


So, I figured it out. Tree positions have to be in 0 to 1 space. So, I just did this:

newTree.position = new Vector3 ( point.x / this.mapWidth, 0, point.z / this.mapDepth );