Unity不使用Mask制作圆形技能CD功能
using UnityEngine;
using UnityEngine.Sprites;
using UnityEngine.UI;
public class CircleImage : Image
{
[SerializeField]
private int segements=100;
[SerializeField]
private float showPercent=1;
protected override void OnPopulateMesh(VertexHelper vh)
{
vh.Clear();
float width = rectTransform.rect.width;
float height = rectTransform.rect.height;
int realSegments = (int)(segements * showPercent);
Vector4 uv = overrideSprite != null ? DataUtility.GetOuterUV(overrideSprite) : Vector4.zero;
float uvWidth = uv.z - uv.x;
float uvHight = uv.w - uv.y;
Vector2 uvCenter = new Vector2(uvWidth * 0.5f, uvHight * 0.5f);
Vector2 convertRatio = new Vector2(uvWidth / width, uvHight / height);
float radian = (2 * Mathf.PI) / segements;
float radius = width * 0.5f;
Vector2 originPos = new Vector2((0.5f - rectTransform.pivot.x) * width, (0.5f - rectTransform.pivot.y) * height);
Vector2 vertPos = Vector2.zero;
UIVertex origin = new UIVertex();
byte temp = (byte)(255 * showPercent);
origin.color = new Color32(temp, temp, temp, 255);
origin.position = originPos;
origin.uv0 = new Vector2(vertPos.x * convertRatio.x + uvCenter.x, vertPos.y * convertRatio.y + uvCenter.y);
vh.AddVert(origin);
int vertexCount = realSegments + 1;
float curRadian = 0;
Vector2 posTermp;
for (int i = 0; i < segements + 1; i++)
{
float x = Mathf.Cos(curRadian) * radius;
float y = Mathf.Sin(curRadian) * radius;
curRadian += radian;
UIVertex vertexTemp = new UIVertex();
if (i < vertexCount)
{
vertexTemp.color = color;
}
else
{
vertexTemp.color = new Color32(60, 60, 60, 255);
}
posTermp = new Vector2(x, y);
vertexTemp.position = posTermp + originPos;
vertexTemp.uv0 = new Vector2(posTermp.x * convertRatio.x + uvCenter.x, posTermp.y * convertRatio.y + uvCenter.y);
vh.AddVert(vertexTemp);
}
int id = 1;
for (int i = 0; i < segements; i++)
{
vh.AddTriangle(id, 0, id + 1);
id++;
}
}
}
![](https://img-blog.csdnimg.cn/direct/8c56d1f453e948a981a3fe69dbb3a25d.png)
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEditor.UI;
using UnityEngine;
[CustomEditor(typeof(CircleImage),true)]
[CanEditMultipleObjects]
public class CircleImageEditor : ImageEditor
{
SerializedProperty _fillPercent;
SerializedProperty _segements;
protected override void OnEnable()
{
base.OnEnable();
_fillPercent = serializedObject.FindProperty("showPercent");
_segements = serializedObject.FindProperty("segements");
}
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
serializedObject.Update();
EditorGUILayout.Slider(_fillPercent, 0, 1, new GUIContent("ShowPercent"));
EditorGUILayout.PropertyField(_segements);
serializedObject.ApplyModifiedProperties();
if (GUI.changed)
{
EditorUtility.SetDirty(target);
}
}
}