Unity 通过Mesh网格渲染绘制图形与字体

发表于2017-10-30
评论0 1.6k浏览

任何一个模型都是由若干网格面组成,而每一个面又有若干个三角形组成,也就是说,模型是由若干个三角形面组成的(字体和图片也是如此);为此,下面就和大家介绍下在Unity开发中通过Mesh网格渲染绘制图形和字体的方法。


组成简单模型的组件需要包含以下几个:



MeshImage脚本代码如下:

using UnityEngine;  
using System.Collections;  
public class MeshImage : MonoBehaviour {  
    // Use this for initialization  
    void Start () {  
        MeshRectangle ();  
    }  
    // 创建一个矩形  
    void MeshRectangle()  
    {  
        // 得到网格渲染器对象  
        MeshFilter mFilter = gameObject.GetComponent<MeshFilter> ();  
        MeshRenderer mRen = gameObject.GetComponent<MeshRenderer> ();  
        //矩形的四个顶点坐标  
        Vector3[] vertices = new Vector3[4];  
        vertices [0] = new Vector3 (0, 0, 0);  
        vertices [1] = new Vector3 (5, 0, 0);  
        vertices [2] = new Vector3 (5, 5, 0);  
        vertices [3] = new Vector3 (0, 5, 0);  
        // 三角形顶点索引  
        int[] triangles = new int[]{0, 1, 2, 2, 3, 0};  
        //每个顶点的法线  
        Vector3[] normals = new Vector3[4];  
        normals [0] = new Vector3 (0, 0, -5);  
        normals [1] = new Vector3 (0, 0, -5);  
        normals [2] = new Vector3 (0, 0, -5);  
        normals [3] = new Vector3 (0, 0, -5);  
        //  UV贴图坐标  
        Vector2[] uvs = new Vector2[4];  
        uvs [0] = new Vector2 (0, 0);  
        uvs [1] = new Vector2 (1, 0);  
        uvs [2] = new Vector2 (1, 1);  
        uvs [3] = new Vector2 (0, 1);  
        //顶点颜色  
        Color32[] colors32 = new Color32[4];  
        colors32 [0] = new Color32 (255, 255, 0, 255);  
        colors32 [1] = new Color32 (255, 255, 0, 255);  
        colors32 [2] = new Color32 (255, 255, 0, 255);  
        colors32 [3] = new Color32 (255, 255, 0, 255);  
        Mesh mesh = new Mesh ();  
        mesh.hideFlags = HideFlags.DontSave;  
        mesh.vertices = vertices;  
        mesh.triangles = triangles;  
        mesh.colors32 = colors32;  
        mesh.uv = uvs;  
        mesh.normals = normals;  
        mFilter.mesh = mesh;  
    }  
    // Update is called once per frame  
    void Update () {  
        MeshRectangle ();  
    }  
}  

通过对以上代码的扩展,运行后的效果如下:



注意:所使用的Shader需要支持顶点色,如NGUI中的Unlit - Text

如社区发表内容存在侵权行为,您可以点击这里查看侵权投诉指引