前情提要:做项目时不时就碰到说要UI从上到下的羽化渐出效果,但好像找插件又没找到这种的,DOTween好像也没这种功能,那只能自己手搓了,但就写多了又觉得烦,干脆点做个小插件吧
下面是效果:
下面是代码,挂在父物体就能用,不需要添加Mask2D
using System;
using System.Collections;
using Unity.VisualScripting.FullSerializer;
using UnityEngine;
using UnityEngine.UI;
public class Mask2DAnimation : MonoBehaviour
{
private RectMask2D rectMask2D;
private RectTransform _rectTransform;
public bool go;
[Header("羽化大小(Px)")]
public Vector2Int eclosion;
[Header("羽化方向(跟出现方向相反)")]
public FeatherDirection featherDirection;
[Header("动画时间")]
public float animationTime;
void Start()
{
_rectTransform = GetComponent<RectTransform>();
rectMask2D = gameObject.AddComponent<RectMask2D>();
rectMask2D.softness = eclosion;
switch (featherDirection)
{
case FeatherDirection.Top:
rectMask2D.padding = new Vector4(0, -eclosion.y, 0, _rectTransform.sizeDelta.y);
break;
case FeatherDirection.Bottom:
rectMask2D.padding = new Vector4(0, _rectTransform.sizeDelta.y, 0, -eclosion.y);
break;
case FeatherDirection.Left:
rectMask2D.padding = new Vector4(_rectTransform.sizeDelta.x, 0, -eclosion.x, 0);
break;
case FeatherDirection.Right:
rectMask2D.padding = new Vector4(-eclosion.x, 0, _rectTransform.sizeDelta.x, 0);
break;
}
// rectMask2D.padding = new Vector4(Left, Bottom, Right, Top);
StartCoroutine(ControlMask());
}
IEnumerator ControlMask()
{
while (true)
{
float xpx = (_rectTransform.sizeDelta.x + eclosion.x) * Time.deltaTime / animationTime;
float ypx = (_rectTransform.sizeDelta.y + eclosion.y) * Time.deltaTime / animationTime;
if (go)
{
switch (featherDirection)
{
case FeatherDirection.Top:
if (rectMask2D.padding.w > -eclosion.y)
{
rectMask2D.padding -= new Vector4(0, 0, 0, ypx);
}
break;
case FeatherDirection.Bottom:
if (rectMask2D.padding.y > -eclosion.y)
{
rectMask2D.padding -= new Vector4(0, ypx, 0, 0);
}
break;
case FeatherDirection.Left:
if (rectMask2D.padding.x > -eclosion.x)
{
rectMask2D.padding -= new Vector4(xpx, 0, 0, 0);
}
break;
case FeatherDirection.Right:
if (rectMask2D.padding.z > -eclosion.x)
{
rectMask2D.padding -= new Vector4(0, 0, xpx, 0);
}
break;
}
}
else
{
switch (featherDirection)
{
case FeatherDirection.Top:
if (rectMask2D.padding.w < _rectTransform.sizeDelta.y)
{
rectMask2D.padding += new Vector4(0, 0, 0, ypx);
}
break;
case FeatherDirection.Bottom:
if (rectMask2D.padding.y < _rectTransform.sizeDelta.y)
{
rectMask2D.padding += new Vector4(0, ypx, 0, 0);
}
break;
case FeatherDirection.Left:
if (rectMask2D.padding.x < _rectTransform.sizeDelta.x)
{
rectMask2D.padding += new Vector4(xpx, 0, 0, 0);
}
break;
case FeatherDirection.Right:
if (rectMask2D.padding.z < _rectTransform.sizeDelta.x)
{
rectMask2D.padding += new Vector4(0, 0, xpx, 0);
}
break;
}
}
yield return null;
}
}
}
public enum FeatherDirection
{
Top,
Bottom,
Left,
Right
}