2010-08-25

在 Unity 3D 裡用 C# Script 產生 Mesh

首先建立一個 C# Script,這裡取名為 SimpleRect.cs,其內容如下(特別注意的是 class name 必須與檔名相同):
using UnityEngine;
using System.Collections;

public class SimpleRect : MonoBehaviour {

    // Use this for initialization
    void Start () {

        Mesh pm = new Mesh();
        pm.Clear();
        
        Vector3[] verts = new Vector3[4];
        verts[0].x = -0.5f;
        verts[0].y = 0.0f;
        verts[0].z = 0.5f;

        verts[1].x = 0.5f;
        verts[1].y = 0.0f;
        verts[1].z = 0.5f;

        verts[2].x = -0.5f;
        verts[2].y = 0.0f;
        verts[2].z = -0.5f;

        verts[3].x = 0.5f;
        verts[3].y = 0.0f;
        verts[3].z = -0.5f;
        pm.vertices = verts;

        int[] tris = new int[6];

        tris[0] = 0;
        tris[1] = 1;
        tris[2] = 2;
        
        tris[3] = 2;
        tris[4] = 1;
        tris[5] = 3;

        pm.triangles = tris;

        pm.RecalculateBounds();
        pm.RecalculateNormals();

        pm.Optimize();

        //建立 GameObject, 並指定 MeshFilter 的 Mesh:
        GameObject go = new GameObject();
        MeshFilter mf = go.AddComponent<meshfilter>();
        mf.mesh = pm;

        MeshRenderer mr = go.AddComponent<meshrenderer>(); 
    }

    // Update is called once per frame
    void Update () {

    }
}

082501
將 SimpleRect.cs 從 Project 拖移至 Hierarchy 視窗的 MainCamera 上


082502
點選 MainCamera 時,可看到 Inspector 裡多了 SimpleRect 的 Script


082503
此時進入 GameMode 就可以看到產生的 Rect

0 意見 :

張貼留言