首页 > 编程语言 > 详细

unity, 用脚本创建mesh

时间:2015-05-22 16:40:29      阅读:232      评论:0      收藏:0      [点我收藏+]

创建一个空gameObject,添加Mesh Filter和Mesh Renderer两个component,再添加一个脚本createMeshScript:

using UnityEngine;
using System.Collections;
[ExecuteInEditMode]
public class createMeshScript : MonoBehaviour {

    void Awake() {

        gameObject.GetComponent<MeshFilter> ().mesh = CreateMesh (1,1);
    }

    Mesh CreateMesh(float width, float height)
    {
        Mesh m = new Mesh();
        m.name = "ScriptedMesh";
        //note: unity is left-hand system
        m.vertices = new Vector3[] {
            new Vector3(-width, -height, 0),
            new Vector3(-width, height, 0),
            new Vector3(width, height, 0),
            new Vector3(width, -height, 0)
        };
        m.uv = new Vector2[] {
            new Vector2 (0, 0),
            new Vector2 (0, 1),
            new Vector2 (1, 1),
            new Vector2 (1, 0)
        };
        m.triangles = new int[] { 0, 1, 2, 0, 2, 3};
        m.RecalculateNormals();
        m.RecalculateBounds();
        return m;
    }
}

此时可以看到Inspector中Mesh Filter->Mesh显示为ScriptedMesh。

此时创建的mesh没有材质,显示为紫色,新建一个Material拖放到Mesh Renderer->Materials->Element 0上,完成mesh的创建。

由于脚本中添加了[ExecuteInEditMode],所以无需运行直接在Scene窗口中就可以看到新创建的mesh。如图:

技术分享

 

另外需要注意的是:

1,unity中是坐标系统是左手系,如果不注意这一点把顶点顺序(法线)搞反了,可能画出来的东西因背面剔除而看不到。

2,mesh.vertices要用局部坐标。

 

unity, 用脚本创建mesh

原文:http://www.cnblogs.com/wantnon/p/4522415.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!