How to fade in UI image in Unity

若如初见. 提交于 2019-12-02 10:38:16

image.material.color is not what you think it is

With a few debug lines I was able to determine that the image material's alpha reports that it is 1 even when I set the image color multiplier to 0.

If I override the curColor to have a 0 and let the loop do its thing, the image never appears either.

This is because this:

Is not image.material.color. It's image.color.

Thus your fixed code would be:

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

Additionally a few other things:

  • Your code does not lerp the color linearly. I'm sure you knew that, and you're probably fine with that, but I figured I'd point it out.
  • You don't need Invoke("startFadein", 1);. You can just call StartCoroutine(FadeIn()); and put yield return new WaitForSeconds(1) at the top.
  • Your image will never actually reach the target value, it'll be close, but not equal. You can fix this by putting curColor.a = targetAlpha; image.color = curColor; after the while loop.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!