Unity - Mesh

From NoskeWiki
Jump to: navigation, search

About

NOTE: This page is a daughter page of: Unity


Unity3D is a multi-platform 3D game engine. This page talks a little bit about how to dynamically draw an edit "Meshes".


Generating a Mesh in Unity

The easiest way to render a custom mesh is to use a 3D program like Cinema 4D and you can import the model file directly. However to dynamically generate a mesh you will want to use the Mesh class.

Below is a snippet of code which generates a single triangle (three points and then connects these points). If you create a new project, save this as "DrawMeshExample.cs" and drag it onto an empty game object at 0,0,0 you should be able to see the triangle create itself when you hit play.

using UnityEngine;
using System.Collections.Generic;
 
public class SimpleMeshDisplay : MonoBehaviour
{
  private Mesh mesh;
  private Material mat;
 
  void Start ()
  {
    mat = new Material(Shader.Find("Self-Illumin/VertexLit"));
    mat.color = new Color(0,1,0);
 
    mesh = new Mesh();
 
    Vector3[] newVertices  = new Vector3[3];  // Setup vertices.
    newVertices[0] = new Vector3(0,0,0);
    newVertices[1] = new Vector3(0,5,0);
    newVertices[2] = new Vector3(5,5,0);
 
    int[] newTriangles = new int[3];      // Map these 3 verticies into one triangle.
    newTriangles[0] = 0;
    newTriangles[1] = 1;
    newTriangles[2] = 2;
 
    mesh.vertices = newVertices;
 
    mesh.triangles = newTriangles;
    //mesh.uv       = newTextureCoord;  // For texture mapping using a Vector2[].
    //mesh.normals  = newNormal;        // For configuring normals using a Vector3[].
    //mesh.colors   = newColorVert;     // Vary color by vertex using a Color[].
    mesh.RecalculateBounds();
    mesh.RecalculateNormals();
  }
 
 
  void Update()
  {
    Graphics.DrawMesh(mesh, transform.localToWorldMatrix, mat, 0);
  }
}


Dynamically Loading Models

Dynamically loading models can be tricky. With Unity Pro, you can apparently use asset bundles to load new parts on request, but to actually load a mesh from a model file on the web is trickier. There's a great article about it here which provides code for loading a OBJ file from a web page at runtime:


Links

  • Unity API:
    • Mesh Class
    • About Meshes - mostly about importing
    • Mesh Components - talks about Mesh Filters and even Text Mesh (for making meshes showing text).
    • Performance of Unity Shaders - explains performance of different shaders (required by the mesh's material), with decreasing order of speed being: Unlit, VertexLit, Diffuse, Normal then the various Specular options.