• Son Luu

Mesh via Scripts in Unity


Today, it's common to build 3D models using softwares specialized for that task. The idea of creating meshes purely using scripts inside Unity has never crossed my mind until today when I saw someone doing it. It actually came across very refreshing to me. As I'm exploring potential application for this skill set, I thought it would be interesting to experiment with the idea to learn more about Unity and using script for a variety of purposes while building virtual interactive spaces.


So below is an attempt to simple draw a triangle inside the scene in Unity, using solely script with C#. It was challenging and was very time-consuming, but I found it very interesting and useful to better understand how the script works in Unity.



The script below ended up running in Unity "okay".




The reason why I know it's not running well is because there is a warning a shown below, and I couldn't find the root cause for it.


The interesting thing was that the script didn't at first for a long time. I kept running the script over and over for a long time, to test if the warning would go away. for about 2 hours while looking up what is wrong with the code. As soon as I almost gave up, the same script that hasn't been running, now runs. But, the warning remains on the console.




Below is the screenshot of the properties of the mesh "Triangle" which include the Mesh Filter which tells the computer how to draw this triangle, and the Mesh Renderer which actually draws the mesh on the scene.





What's interesting is a Material is needed in order for the Triangle to show up. So, at the end, I need to create a Material property, chose option Unlit (for Shader) and then chose Color, and then attach this Material to the triangle object and picked a color for it.


The points (which is the triangle mesh) were so small, so they can't really be seen here in the scene. But, the next step may be to draw actual lines between the points to form a triangle.



So, now I changed the script from drawing points to actually drawing a triangle by changing the method for MeshTopology from MeshTopology.Points to MeshTopology.Triangles. The setup of the Vertices need to be in clock-wise fashion, and in this case, it's already in the correct format (line 40, 41, 42).




So the result did yield a triangle. I then created another material for this triangle and picked a yellow color for it, so this time, we can actually see a triangle it's not just points, but a shape that is formed.