Set Y points of vertices on ground.

I’m trying to create a grid tile and set it on the ground. Here is my script so far:

Mesh mesh = new Mesh();

Vector3[] vertices = new Vector3[4];
vertices[0] = new Vector3(-tileWidth/4, 0, tileWidth/4); //top-left
vertices[1] = new Vector3(tileWidth/4, 0, tileWidth/4); //top-right
vertices[2] = new Vector3(-tileWidth/4, 0, -tileWidth/4); //bottom-left
vertices[3] = new Vector3(tileWidth/4, 0, -tileWidth/4); //top-right

mesh.vertices = vertices;

int[] triangles = new int[6]{0,1,2,3,2,1};
mesh.triangles = triangles;

Vector2[] uvs = new Vector2[4]; // setting UVs
uvs[0] = new Vector2(0,1); //top-left
uvs[1] = new Vector2(1,1); //top-right
uvs[2] = new Vector2(0,0); //bottom-left
uvs[3] = new Vector2(1,0); //bottom-right

mesh.uv = uvs;

When setting the vertices, instead of setting y to 0, I would like to cast a ray from each vertex in the -Vector3.up direction and set the vertex’s y to hit.point.y in global space.

How do I achieve this?

Easiest way to do that would be to create a function to do the raycast for a single XZ position:

Vector3 getVertexPosFromXZ(float x, float z) {
    RaycastHit hit;
    if (Physics.Raycast(new Vector3(x, 99999f, z), -Vector3.up, out hit)) {
        return new Vector3(x, hit.point.y, z);
    } else {
        return new Vector3(x, 0f, z); // or whatever the default should be

and then call it four times:

vertices[0] = getVertexPosFromXZ(-tileWidth/4, tileWidth/4); //top-left
vertices[1] = getVertexPosFromXZ(tileWidth/4, tileWidth/4); //top-right
vertices[2] = getVertexPosFromXZ(-tileWidth/4, -tileWidth/4); //bottom-left
vertices[3] = getVertexPosFromXZ(tileWidth/4, -tileWidth/4); //top-right