These are my notes on how to make a Mesh with Materials from pure C# code in Unity.
Space — A coordinated system to define points.
UV — A 2d Space normalized based on the image’s size. The definition is always UV = (0,0) is the origin and (1,1) is the top left in image space. To convert an image point from pixels to UV, have U = (chosen pixel x position)/(Image Pixel Width) and V = (chosen pixel y position)/(Image Pixel Height). A Loose idea is that the UV value is the “%” towards the top right of a picture.
Steps seem to be:
- Generate a GameObject( aka GO ).
- Generate Geometry.
- Geometry is stored in the mesh property of a MeshFilter component attached to a GameObject.
- Generate Texture.
- Texture is stored in the material property of a MeshRenderer component attached to a GameObject.
Step 1: Make a gameobject with the needed components:
Two different ways to do this: method one:
Add this decoration to the class that will be your GO.
Method two — use the API to add at runtime.
gameObject.AddComponent<MeshFilter>().mesh = mesh; gameObject.AddComponent<MeshRenderer>().material = material;
Step 2: Generate Geometry.
Meshes are made of a handful of ideas. This means you have a handful of things to figure out to make a mesh:
- Where are the vertices in XYZ.
- What are the right normals to use per vertex.
- Which vertices should be duplicated to handle different faces using them.
- What is each vertex’s UV.
- What is each vertex’s curvature.
- What subfacets should your create to maximize your texture.
The first is that meshes are made of triangles. You add the points in Unity’s world space, then link them in triangles by using the indices of each vertex in an array of Vector3.
NOTE. You can generate submeshes in a mesh. You specify the array of vertexes as normal, but instead of directly adding trianges, instead you set Mesh.SubmeshCount to your count of submeshes. Now, add triangles to each submesh instead of the main mesh. Example code:
Mesh output = new Mesh();
output.subMeshCount = 2;
// if you’re not using submeshes, you can just add triangles by:
output.triangles = m_TriangleArray;
One part of generating the geometry is generation of the UV axis per vertex. Here’s a good URL for UV generation on sphere’s: https://gamedevdaily.io/four-ways-to-create-a-mesh-for-a-sphere-d7956b825db4#.ga3iofdlb
For cubes, it’s easier. There’s yet another method for cylinders. It seems cube, cylinder, and sphere are the three approximations people use for generating their UV axis information. You’ll use the vertex and normals to figure out the right axis position for UV.
Step 3: Generate texture.