Script to Extrude 2D Polygon

I’m creating a flat polygon mesh via script. Easy enough, but I want to stick a mesh collider on it, and that doesn’t work too well unless the mesh has depth. So, I’m looking for a generic way to extrude a flat mesh a couple of units in the z-axis.

Could someone provide some code for doing this?

Duplicating the triangles and flipping them to get the back face would be easy, but how would I then generate the sides?

I don’t know of any example code for this off the top of my head, although I’m sure you could find some. However, as far as procedural mesh generation goes, this is one of the easier problems to solve.

As you suggested, the first step will be to duplicate the polygon vertices and offset them by some distance along the polygon normal. If, say, the polygon is an octagon, the indices of the original vertices will be 0-7, and the indices of the new vertices will be 8-15. The triangles for the new polygon should be the same as those of the original polygon, except with the winding reversed and the indices offset by 8.

You now need to create N2 new triangles, N being the number of sides (8 in this case). That means N23 extra indices, so the total number of indices for the extruded mesh should be the original number of indices * 2, plus N2*3. (This is all off the top of my head, but I’m pretty sure it’s correct.)

All that remains is to create the indices for the side triangles. This sort of thing can be a bit tedious, but if you write a lot of code for manipulating meshes, you get used to it. The key is to identify the pattern and then express it in code. (Note that the % operator comes in handy when iterating over a ‘loop’ of vertices.) It would probably help to draw a simple example on paper, label the vertices according to their indices, and then look for the pattern in how the side triangles are constructed.

Maybe someone will provide a link or post a complete code example, but in lieu of that, the above should be enough to get you started.

There is an example in the procedural resources that shows how to extrude a polygon.

Oops, I guess all that typing I did was unnecessary. (I’m familiar with the procedural examples, but I didn’t remember there being a specific example for extruding a polygon - my bad.)