UGUI动态生成Mesh图形、赋予贴图和颜色

新建一个场景,加一个空对象UGUI动态生成Mesh图形、赋予贴图和颜色_第1张图片

在GameObject上分别添加MeshFilter,MeshRendererUGUI动态生成Mesh图形、赋予贴图和颜色_第2张图片

在GameObject上挂上一个脚本UGUI动态生成Mesh图形、赋予贴图和颜色_第3张图片

效果:UGUI动态生成Mesh图形、赋予贴图和颜色_第4张图片UGUI动态生成Mesh图形、赋予贴图和颜色_第5张图片

脚本:

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class MyMeshTest : MonoBehaviour {
    VertexHelper vertexhelper = new VertexHelper();
    private Mesh mesh;
    public Color color;
    public Texture texture;
    private MeshFilter meshfilter;
    private MeshRenderer meshrenderer;
	private MeshRenderer MeshRenderer {
        get {
            if (meshrenderer == null) {
                meshrenderer = GetComponent();
            }
            return meshrenderer;
        }
    }
    private MeshFilter MeshFilter {
        get {
            if (meshfilter==null) {
                meshfilter = GetComponent();
            }
            return meshfilter;
        }
    }
	void Start () {
        MeshTest();
	}
	
	// Update is called once per frame
	void Update () {
        MeshRenderer.material.color = color;//实时在编辑下改变颜色
    }
    public void MeshTest() {
        mesh = new Mesh();
        vertexhelper.Clear();
        //添加5个顶点
        vertexhelper.AddVert(new Vector2(0,0),color,new Vector2(0,0));
        vertexhelper.AddVert(new Vector2(0, 1), color, new Vector2(0, 1));
        vertexhelper.AddVert(new Vector2(1, 1), color, new Vector2(1, 1));
        vertexhelper.AddVert(new Vector2(1, 0), color, new Vector2(1, 0));
        vertexhelper.AddVert(new Vector2(1.5f, 0), color, new Vector2(1.5f, 0));
        //添加3个三角面
        vertexhelper.AddTriangle(0,1,2);
        vertexhelper.AddTriangle(2,3,0);
        vertexhelper.AddTriangle(2,4,0);
        vertexhelper.FillMesh(mesh);//填充网格
        MeshFilter.mesh = mesh;
        // MeshRenderer.material.color = color;
        MeshRenderer.material.mainTexture = texture;//贴图
    }
}

你可能感兴趣的:(UGUI动态生成Mesh图形、赋予贴图和颜色)