/* 最后修改时间: 主题: 功能: 作者: */ using FZY; using System.Collections; using System.Collections.Generic; using System.Text; using UnityEngine; using UnityEngine.UI; using UnityEditor; using System; [RequireComponent(typeof(Graphic))] public class NewBehaviourScript : BaseMeshEffect { [SerializeField] private Color _topColor = Color.white;//顶部颜色 [SerializeField] private Color _buttomColor = Color.white;//底部颜色 [SerializeField, Range(-1f, 1f)] private float _colorScale = 0f; //颜色过度的比例 public override void ModifyMesh(VertexHelper vh) { //判断当前对象是否为激活状态 if (!IsActive()) return; List<UIVertex> vList = new List<UIVertex>(); vh.GetUIVertexStream(vList); ModifyVertices(vList); vh.Clear(); vh.AddUIVertexTriangleStream(vList); } void ModifyVertices(List<UIVertex> vList) { if (IsActive() == false || vList == null || vList.Count == 0) { return; } //记录初始顶点的纵坐标 float topPosY = vList[0].position.y; float buttomPosY = vList[0].position.y; //遍历所有顶点,找出最上与下的,用来下面做颜色差值 for (int i = 0; i < vList.Count; i++) { UIVertex temp = vList[i]; topPosY = Mathf.Max(topPosY, temp.position.y); buttomPosY = Mathf.Min(buttomPosY, temp.position.y); } //计算整个文本组件顶点的垂直间距 float intervalHeight = topPosY - buttomPosY; //开始修改顶点 for (int i = 0; i < vList.Count; i++) { UIVertex temp = vList[i]; //颜色差值 颜色不受到源字体颜色的影响 temp.color = Color.Lerp(_buttomColor, _topColor, (intervalHeight > 0 ? (temp.position.y - buttomPosY) / intervalHeight : 0) + _colorScale); //如果想让颜色受到源字体颜色的影响,可以使用下面这句 //temp.color=temp.color* Color.Lerp(_buttomColor, _topColor, (intervalHeight > 0 ? (temp.position.y - buttomPosY) / intervalHeight : 0) + _colorScale); //再赋值会原来的顶点,抛回去绘制 vList[i] = temp; } } }
参考了一些大神们的代码,加上自己的理解,了解了十有八九
最后让我们来看一下最后的效果
脚本只需要挂到字体或颜色组件上就可以看到效果了
有不懂可以在详情问我