示例
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.Serialization;
/// <summary>
/// Alpha渐变
/// </summary>
public class UITweenAlpha : MonoBehaviour
{
public enum ComponentType
{
Graphic,
Text
}
public ComponentType componentType;
[SerializeField]
private bool active = false;
[Tooltip("延迟执行")]
public float delayTime = 0;
public float from = 1;
public float to = 1;
[Tooltip("持续时间")]
public float duration = 3;
public Graphic graphic;
[Serializable]
// 定义缓动完成后要触发的事件
public class TweenCompletedEvent : UnityEvent { }
// 防止序列化变量重命名后丢失引用
[FormerlySerializedAs("onCompleted")]
[SerializeField]
private TweenCompletedEvent m_OnCompleted = new TweenCompletedEvent();
private float t = 0;
private float escapeTime = 0;
private Text text;
private void Awake()
{
if (graphic == null)
graphic = this.GetComponent<Graphic>();
if (componentType == ComponentType.Text)
text = this.GetComponent<Text>();
}
void Update()
{
if (!active)
return;
escapeTime += Time.deltaTime;
if (escapeTime < delayTime)
return;
if (duration <= 0 || t > duration)
return;
if (ComponentType.Graphic == componentType)
{
if (graphic == null)
return;
t += Time.deltaTime;
float alpha = Mathf.Lerp(from, to, t / duration);
Color c = graphic.color;
c.a = alpha;
graphic.color = c;
}
else
{
if (text == null)
return;
t += Time.deltaTime;
float alpha = Mathf.Lerp(from, to, t / duration);
Color c = text.color;
c.a = alpha;
text.color = c;
}
if (t >= duration)
{
active = false;
m_OnCompleted.Invoke();
}
}
public void SetAlpha(float a)
{
if (componentType == ComponentType.Graphic)
{
Color c = graphic.color;
c.a = a;
graphic.color = c;
}
else
{
Color c = text.color;
c.a = a;
text.color = c;
}
}
public void Reset()
{
SetAlpha(from);
}
public void Play()
{
t = 0;
escapeTime = 0;
active = true;
}
public void Stop()
{
t = 0;
escapeTime = 0;
active = false;
}
public void Pause()
{
active = false;
}
public void Resume()
{
active = true;
}
}