Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Custom UI Meshes script by @MinionsArt
- using UnityEngine;
- using UnityEngine.UI;
- [ExecuteAlways]
- [RequireComponent(typeof(CanvasRenderer))]
- public class UIMeshRenderer : MaskableGraphic
- {
- [SerializeField]
- Mesh mesh;
- [SerializeField]
- bool preserveAspect;
- protected override void OnEnable()
- {
- base.OnEnable();
- SetVerticesDirty();
- SetMaterialDirty();
- }
- protected override void OnRectTransformDimensionsChange()
- {
- base.OnRectTransformDimensionsChange();
- SetVerticesDirty();
- SetMaterialDirty();
- }
- protected override void OnPopulateMesh(VertexHelper vh)
- {
- vh.Clear();
- if (mesh == null) return;
- Rect rect = rectTransform.rect;
- // handle preserving aspect
- if (preserveAspect && mesh.bounds.extents.sqrMagnitude > 0f)
- {
- float meshRatio = mesh.bounds.extents.x / mesh.bounds.extents.y;
- float rectRatio = rect.width / rect.height;
- if (meshRatio > rectRatio)
- {
- float oldHeight = rect.height;
- rect.height = rect.width / meshRatio;
- rect.y += (oldHeight - rect.height) * rectTransform.pivot.y;
- }
- else
- {
- float oldWidth = rect.width;
- rect.width = rect.height * meshRatio;
- rect.x += (oldWidth - rect.width) * rectTransform.pivot.x;
- }
- }
- // scale to rect transform size
- float scaleX = rect.width / mesh.bounds.size.x;
- float scaleY = rect.height / mesh.bounds.size.y;
- // mesh center in case of offcenter pivot
- Vector3 center = mesh.bounds.center;
- Vector3[] verts = mesh.vertices;
- Vector2[] uvs = mesh.uv;
- // check if we have vertex colors assigned
- Color32[] colors = mesh.colors32.Length == verts.Length ? mesh.colors32 : null;
- for (int i = 0; i < verts.Length; i++)
- {
- // use scale on all vertices and offset
- Vector3 vert = verts[i] - center;
- vert.x *= scaleX;
- vert.y *= scaleY;
- vert.z *= scaleX;
- // use color assigned in graphic if theres no vertex color
- Color32 col = colors != null ? colors[i] : (Color32)this.color;
- // set new vertices
- vh.AddVert(vert, col, uvs[i]);
- }
- // set triangles
- int[] tris = mesh.triangles;
- for (int i = 0; i < tris.Length; i += 3)
- vh.AddTriangle(tris[i], tris[i + 1], tris[i + 2]);
- }
- #if UNITY_EDITOR
- protected override void OnValidate()
- {
- base.OnValidate();
- SetVerticesDirty();
- SetMaterialDirty();
- }
- #endif
- }
Advertisement
Add Comment
Please, Sign In to add comment