Search Unity

Unity UI Efficient way to use plain Mesh objects in GUI

Discussion in 'UGUI & TextMesh Pro' started by JasonSpine, Sep 21, 2019.

  1. JasonSpine

    JasonSpine

    Joined:
    May 14, 2015
    Posts:
    20
    Hello, I wrote a class to use simple single-colored mesh shapes in GUI, instead of using Sprites.

    It works!

    I just don't know if it's the most efficient way to put my mesh data in Graphic object.
    Copying vertices and triangles to vertex helper doesn't seem to be the best way :(

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5.  
    6. namespace Menu
    7. {
    8.     public class UI_MeshRenderer : Graphic
    9.     {
    10.         public Mesh meshToRender;
    11.         public float scale = 1.0f;
    12.  
    13.         protected override void OnPopulateMesh(VertexHelper vh)
    14.         {
    15.             vh.Clear();
    16.  
    17.             if (meshToRender == null)
    18.             {
    19.                 return;
    20.             }
    21.  
    22.             UIVertex vert = new UIVertex();
    23.             vert.color = this.color;
    24.  
    25.             Vector3[] verts = meshToRender.vertices;
    26.             int[] tris = meshToRender.triangles;
    27.  
    28.             Vector3 centerDelta = meshToRender.bounds.center;
    29.  
    30.             float maxCoord = 0.0001f;
    31.             for (int i = 0; i < verts.Length; i++)
    32.             {
    33.                 verts[i] -= centerDelta;
    34.  
    35.                 maxCoord = Mathf.Max(Mathf.Abs(verts[i].x), Mathf.Abs(verts[i].y), maxCoord);
    36.             }
    37.  
    38.             float meshScaler = scale * (0.5f * Mathf.Min(rectTransform.rect.width, rectTransform.rect.height)) / maxCoord;
    39.  
    40.             for (int i = 0; i < verts.Length; i++)
    41.             {
    42.                 vert.position = verts[i] * meshScaler;
    43.                 vh.AddVert(vert);
    44.             }
    45.  
    46.             for (int i = 0; i < tris.Length; i += 3)
    47.             {
    48.                 vh.AddTriangle(tris[i], tris[i + 1], tris[i + 2]);
    49.             }
    50.         }
    51.  
    52.         protected override void OnRectTransformDimensionsChange()
    53.         {
    54.             base.OnRectTransformDimensionsChange();
    55.  
    56.             SetVerticesDirty();
    57.             SetMaterialDirty();
    58.         }
    59.     }
    60. }