Saturday, March 7, 2015

Unity Create Mesh Using Script

Okay, when I try to create a minecraft game by using the instantiate cube method, the game basically crash because if you try to instantiate 5000 cube, the computer simply cannot handle, the other way to do this is to create the mesh using script where you can ask the computer to slowly create mesh and only show the face that your camera see, and ignoring the rest

Lets begin

Step1: Open Unity

Step2: Create an Empty Object, move position to 0,0,0

Step3: Add Mesh Filter and Mesh Renderer to the empty object

Step4: Add a new script, "scratch.cs" to the empty object

Step5: The script as below

////////////////////inside scratch.cs/////////////////////////////////
using UnityEngine;
using System.Collections;

public class scratch : MonoBehaviour 
{



    public float height=50f;
    public float width=50f;


    // Use this for initialization
    void Start () 
    {
        MeshFilter mf = GetComponent<MeshFilter>();
        Mesh mesh;
        mesh = new Mesh();
        mf.mesh=mesh;

        //create vertices
        Vector3 [] vert = new Vector3[4]
        { new Vector3(0,0,0),new Vector3(width,0,0),new Vector3(0,height,0),new Vector3(width,height,0) };





        //create triangle

        int [] tri = new int[6];
        tri[0] = 0;
        tri[1] = 2;
        tri[2] = 1;
        tri[3] = 2;
        tri[4] = 3;
        tri[5] = 1;


        //create normal

        Vector3 [] norm = new Vector3[4];

        norm[0]= -Vector3.forward;
        norm[1]= -Vector3.forward;
        norm[2]= -Vector3.forward;
        norm[3]= -Vector3.forward;

        //create uv
    
        Vector2 [] uv = new Vector2[4];

        uv[0] = new Vector2(0,0);
        uv[1] = new Vector2(1,0);
        uv[2] = new Vector2(0,1);
        uv[3] = new Vector2(1,1);

        //all into mesh
        mesh.vertices=vert;
        mesh.triangles=tri;
        mesh.normals =norm;
        mesh.uv=uv;
    }
    

}

////////////////////////////////////////////

Explanation:
1. for any mesh, you need 
a) Vertices (the coordinate point in 3D world)
b) Triangles (all 3D face is build from triagles)
c) Normals (the face that reflect light and got color )
d) UV (the face that let you put texture)

-Vertices store inside a Vector3 List, for a square face, you got 4
- Triangles store inside a integer List, 3 index point for each triagle, for a square face, you need 6 index point
- Normal store inside a Vector3 List, for a square face, you got 4 same as vertices
- UV store inside a Vector2 List, for a square face, you got 4

after you done all the hardcoding, put all this 4 important data into your mesh, and your mesh will be shown on screen



Step6: Run your game and you can see you just create a square face from script

No comments:

Post a Comment