Question by 
               monkaS98 · Mar 28, 2018 at 08:50 AM · 
                scripting problemterrainterrain-trees  
              
 
              How to randomly spawn GameObject on a Terrain
Hello, I have an issue with my script - I want to spawn random amount of trees on a terrain. The problem is - trees just ignore the terrain and spawn inside of it, but not on a terrain. Please, help! Here's my script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TreeSpawner : MonoBehaviour {
 public GameObject Tree;
 public Terrain terrain;
 private int terrainWidth;
 private int terrainLength;
 private int terrainPosX;
 private int terrainPosZ;
 void Start () {
     terrainWidth = (int)terrain.terrainData.size.x;
     terrainLength = (int)terrain.terrainData.size.z;
     terrainPosX = (int)terrain.transform.position.x;
     terrainPosZ = (int)terrain.transform.position.z;
 }
 void Update () {
     int randNumber = Random.Range (50, 100);
     if (Input.GetKeyDown (KeyCode.Space)) {
         foreach (Transform child in gameObject.transform) {
             GameObject.Destroy (child.gameObject);
         }
         for (int i = 0; i < randNumber; i++) {
             int posX = Random.Range (terrainPosX, terrainPosX + terrainWidth);
             int posZ = Random.Range (terrainPosZ, terrainPosZ + terrainLength);
             float posY = Terrain.activeTerrain.SampleHeight (new Vector3 (posX, 0, posZ));
             GameObject newTree = (GameObject)Instantiate (Tree, new Vector3 (posX,posY,posZ), Quaternion.identity);
             newTree.transform.parent = transform;
         }
     }
 }
 
               }
               Comment
              
 
               
              Dont have time to read you script but if they spawn inside the terrain, then you could do a sampleheight at the tree position and assign the y value to the terrain height
Your answer