如何在 Unity 中淡入 UI 图像

How to fade in UI image in Unity

我想将 UI 图像从透明 (alpha=0) 淡入到 alpha=1,我认为我的方法应该是正确的,但它不起作用,图像没有改变。

这是我为此尝试使用的代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Fadein : MonoBehaviour {


    public float FadeRate;
    private Image image;
    private float targetAlpha;

    // Use this for initialization
    void Start()
    {
        image = GetComponent<Image>();
        Material instantiatedMaterial = Instantiate<Material>(image.material);
        image.material = instantiatedMaterial;
        targetAlpha = image.material.color.a;

        Invoke("startFadein", 1);

    }

    IEnumerator FadeIn()
    {
        targetAlpha = 1.0f;
        Color curColor = image.material.color;
        while (Mathf.Abs(curColor.a - targetAlpha) > 0.0001f)
        {
            curColor.a = Mathf.Lerp(curColor.a, targetAlpha, FadeRate * Time.deltaTime);
            image.material.color = curColor;
            yield return null;
        }
    }

    void startFadein()
    {

        StartCoroutine(FadeIn());
    }
}

图片没有变化。但是我尝试使用这段代码淡出,从 1 到 0,它只是工作,我不知道为什么淡入不起作用?

image.material.color 不是你想的那样

通过一些调试行,我能够确定图像 material 的 alpha 报告它是 1,即使我将图像颜色倍增设置为 0。

如果我将 curColor 重写为 0 并让循环执行其操作,图像也不会出现。

这是因为:

不是image.material.color。这是 image.color.

因此您的固定代码为:

IEnumerator FadeIn() {
    targetAlpha = 1.0f;
    Color curColor = image.color;
    while(Mathf.Abs(curColor.a - targetAlpha) > 0.0001f) {
        Debug.Log(image.material.color.a);
        curColor.a = Mathf.Lerp(curColor.a, targetAlpha, FadeRate * Time.deltaTime);
        image.color = curColor;
        yield return null;
    }
}

另外还有一些其他的东西:

  • 您的代码没有对颜色进行线性渐变。我相信你知道这一点,你可能对此没有意见,但我想我会指出来。
  • 你不需要 Invoke("startFadein", 1);。您可以只调用 StartCoroutine(FadeIn()); 并将 yield return new WaitForSeconds(1) 放在顶部。
  • 您的图像永远不会真正达到目标值,它会接近但不相等。您可以通过在 while 循环之后放置 curColor.a = targetAlpha; image.color = curColor; 来解决此问题。