【问题标题】:Unity fade image alpha over timeUnity 随着时间推移淡化图像 alpha
【发布时间】:2016-10-04 09:36:03
【问题描述】:

我想逐渐而不是立即更改我的 UI 图像的 alpha。到目前为止,我立即淡化图像 alpha 的代码如下

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 会立即下降。

我做错了什么?

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    使用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;
        }
    }
    

    希望对你有帮助

    【讨论】:

    • 感谢您的帮助,我不想修改它,以便在图像褪色时,它可以恢复为全彩色。我怎么能这样做?
    【解决方案2】:

    您也可以使用像 Dotween 这样的补间引擎,然后像这样简单地使用它:

    image.DOFade(1, 0.5f)

    Dotween 有很多扩展方法可以帮助您,请参阅文档。 http://dotween.demigiant.com/documentation.php

    DOColor(Color to, float duration) DOFade(float to, float duration)

    【讨论】:

      猜你喜欢
      • 2015-06-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多