How would I instantiate objects on a mesh?


I have a mesh (terrain), and I want to instantiate objects (trees) on it. Unfortunately, my knowledge of C# limits me. :frowning:

I’ve heard of using raycasts, if this is the solution, how would I go about doing that?

For a terrain mesh, the easiest way is to pick a random point in the XZ plane of the terrain (accessible through Renderer.bounds) and do a raycast straight downwards starting from just above the highest point in the terrain (also accessible through Renderer.bounds).

For example, to get a random point on the terrain on which a tree could be spawned, it would look something like this:

Renderer r = GetComponent<Renderer>(); // assumes the terrain is in a mesh renderer on the same GameObject
float randomX = Random.Range(r.bounds.min.x, r.bounds.max.x);
float randomZ = Random.Range(r.bounds.min.z, r.bounds.max.z);

RaycastHit hit;
if (Physics.Raycast(new Vector3(randomX, r.bounds.max.y + 5f, randomZ), -Vector3.up, out hit)) {
    // the raycast hit, the point on the terrain is hit.point, spawn a tree there
} else {
    // the raycast didn't hit, maybe there's a hole in the terrain?

A bit old I know, but this is very close to what I’m doing, except sometime when I instantiate my object, they spawn halfway into the mesh instead of on its surface.
Is there any way to avoid this?