Place On Ground

How do I modify this script so that it places the object on the terrain, because it currently places it somewhat in the air.


        public var distance = 5;
        public var prefab : Transform;
        public var prefab2 : Transform;
        function OnGUI ()
        if (GUI.Button(Rect(25,25,100,30), "Place Cah"))
        var newPrefab=Instantiate(prefab,transform.position+transform.forward*distance,transform.rotation);
        newPrefab.transform.position = transform.position + transform.forward * distance;
        newPrefab.transform.rotation = transform.rotation;
        if (GUI.Button(Rect(125,25,100,30), "Place Uziii"))
        var newPrefab2=Instantiate(prefab2,transform.position+transform.forward*distance,transform.rotation);
        newPrefab2.transform.position = transform.position + transform.forward * distance;
        newPrefab2.transform.rotation = transform.rotation;

You could ray-cast downwards from the object you want to place. If it hits the ground, you place the object to the collision position.

If you want to ray-cast only the terrain, don’t forget to put it in its separate layer, otherwise you might receive information about other objects.