随着时间的推移Unity淡入图像alpha [英] Unity fade image alpha over time

查看:109
本文介绍了随着时间的推移Unity淡入图像alpha的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想逐渐而不是立即更改UI图像的Alpha.到目前为止,我立即使我的图像的Alpha褪色的代码如下

I'm wanting to change the alpha of my UI Images gradually instead of instantly. So far my code for fading the alpha of my image instantly is as follows

public void Highlight()
{
    foreach (Image image in imagesToHighlight)
    {
        Color c = image.color;
        if(c.a < maxColor)
        {
            c.a = maxColor;
        }

        image.color = c;
    }

    foreach (Image image in imagesToFade)
    {
        Color c = image.color;
        if(c.a > halfColor)
        {
            c.a = halfColor;
        }
        image.color = c; 

    }

}

上面的代码可以正常工作,但是我正在努力修改我的代码,以使其不能立即执行,而是需要一两秒钟来缓慢执行.我尝试将行c.a = maxColor;更改为c.a--,以查看图像是否会持续缓慢消失,但是alpha会立即下降.

The above code works fine, but I'm struggling to modify my code so that instead of doing it instantly, it does it slowly over a second or two. I've tried changing the line c.a = maxColor; to c.a-- in order to see if the image would continually fade out slowly but the alpha just instantly drops.

我在做什么错了?

推荐答案

使用Coroutine来实现.像这样:

淡出:

private YieldInstruction fadeInstruction = new YieldInstruction();
IEnumerator FadeOut(Image image)
{
    float elapsedTime = 0.0f;
    Color c = image.color;
    while (elapsedTime < fadeTime)
    {
        yield return fadeInstruction;
        elapsedTime += Time.deltaTime ;
        c.a = 1.0f - Mathf.Clamp01(elapsedTime / fadeTime);
        image.color = c;
    }
}

您可以这样使用它:

foreach (Image image in imagesToFade)
    StartCoroutine(FadeOut(image));

淡入:

IEnumerator FadeIn(Image image)
{
    float elapsedTime = 0.0f;
    Color c = image.color;
    while (elapsedTime < fadeTime)
    {
        yield return fadeInstruction;
        elapsedTime += Time.deltaTime ;
        c.a = Mathf.Clamp01(elapsedTime / fadeTime);
        image.color = c;
    }
}

希望这会有所帮助

这篇关于随着时间的推移Unity淡入图像alpha的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆