最终效果如下:
一:判断Alpha
当Alpha值到达0或者1时,立即切换状态
using UnityEngine;
using UnityEngine.UI;
public class Blink : MonoBehaviour
{
public float blinkSpeed;//闪烁速度
private bool isAddAlpha;//是否增加透明度
private Image img;//指向自身图片
private void Start()
{
img = GetComponent<Image>();
}
private void Update()
{
if (isAddAlpha)
{
img.color += new Color(0, 0, 0, Time.deltaTime * blinkSpeed);
if (img.color.a >= 1)
{
img.color = new Color(img.color.r, img.color.g, img.color.b, 1);
isAddAlpha = false;
}
}
else
{
img.color -= new Color(0, 0, 0, Time.deltaTime * blinkSpeed);
if (img.color.a <= 0)
{
img.color = new Color(img.color.r, img.color.g, img.color.b, 0);
isAddAlpha = true;
}
}
}
}
二:判断Timer
当Alpha值到达0或1时,不立即切换状态,而是通过计时器判断
using UnityEngine;
using UnityEngine.UI;
public class Blink : MonoBehaviour
{
public float blinkSpeed = 5;//闪烁速度
private float timer;//计时器
public float timeval = 1;//时间间隔
private Image img;//指向自身图片
private void Start()
{
img = GetComponent<Image>();
}
private void Update()
{
timer += Time.deltaTime;
if (isAddAlpha)
{
img.color += new Color(0, 0, 0, Time.deltaTime * blinkSpeed);
if (timer >= timeval)
{
img.color = new Color(img.color.r, img.color.g, img.color.b, 1);
isAddAlpha = false;
timer = 0;
}
}
else
{
img.color -= new Color(0, 0, 0, Time.deltaTime * blinkSpeed);
if (timer >= timeval)
{
img.color = new Color(img.color.r, img.color.g, img.color.b, 0);
isAddAlpha = true;
timer = 0;
}
}
}
}