- Home /
Creating a 3D Plane Mesh Without a Filled Center
I was wondering if anyone knew how to create a 3D mesh plane in Unity that doesn't not have a filled center, much like the UI Image component that doesn't have a center, but edges only?
Here is the 2D Unity GUI equivalent of what I'm trying to do with a 3D plane:
Answer by cjdev · Aug 18, 2015 at 09:07 AM
Without really knowing what it is you're trying to do it's a bit difficult to give you a definitive answer, but the basics of procedural mesh generation should get you started. Here is an example that creates a plane of 3x3 squares with the middle square missing:
List<Vector3> verts = new List<Vector3>();
List<int> tris = new List<int>();
for (int i = 0; i < 4; i++) //Creates a grid of squares 3 X 3 with a hole
{
for (int j = 0; j < 4; j++)
{
verts.Add(new Vector3(i, 0.5f, j)); //Adds each new vertex in the plane
//Skip if four vertices cant be connected with tris
if (i == 0 || j == 0 || (i == 2 && j == 2)) continue;
//Adds the index of the three vertices in order to make up each of the two tris
tris.Add(4 * i + j); //Top right
tris.Add(4 * i + j - 1); //Bottom right
tris.Add(4 * (i - 1) + j - 1); //Bottom left - First triangle
tris.Add(4 * (i - 1) + j - 1); //Bottom left
tris.Add(4 * (i - 1) + j); //Top left
tris.Add(4 * i + j); //Top right - Second triangle
}
}
Vector2[] uvs = new Vector2[verts.Count];
for (var i = 0; i < uvs.Length; i++) //Give UV coords X,Z world coords
uvs[i] = new Vector2(verts[i].x, verts[i].z);
GameObject plane = new GameObject("ProcPlane"); //Create GO and add necessary components
plane.AddComponent<MeshFilter>();
plane.AddComponent<MeshRenderer>();
Mesh procMesh = new Mesh();
procMesh.vertices = verts.ToArray(); //Assign verts, uvs, and tris to the mesh
procMesh.uv = uvs;
procMesh.triangles = tris.ToArray();
procMesh.RecalculateNormals(); //Determines which way the triangles are facing
plane.GetComponent<MeshFilter>().mesh = procMesh; //Assign Mesh object to MeshFilter
You pretty much gave me the base for what I need. I was trying to do a 9-sliced mesh plane. I didn't realize it's just 9 different planes re-sized. Here's a similar answer, but with more control to the edge planes.