如何在Unity中淡化UI图像 [英] How to fade in UI image in Unity
问题描述
我想将UI图像从透明(alpha = 0)渐变为alpha = 1,我认为我的方法应该是正确的,但是它不起作用,图像没有变化.
I want to fadein a UI image from transparent(alpha=0) to alpha=1, i thought my approach should be right, but it doesn't work, the image is not changing.
这是我尝试执行的代码:
This is the code that i tried for doing that:
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进行淡入淡出,它只是起作用了,我不知道为何淡入淡出不起作用?
The image is not changing. But i tried fadeout by using this code, from 1 to 0, it just worked, i have no idea why the fadein doesn't work?
推荐答案
image.material.color
不是您想的那样
使用几行调试行,即使将图像颜色倍数设置为0,我也能够确定图像材料的alpha报告它是1
.
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.
如果我将curColor
改写为0,然后让循环执行该操作,则图像也不会出现.
If I override the curColor
to have a 0 and let the loop do its thing, the image never appears either.
这是因为:
不是image.material.color
.它是 image.color
.
Is not image.material.color
. It's 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)
放在顶部. - 您的图像将永远不会真正达到目标值,它将接近但不相等.您可以通过将
curColor.a = targetAlpha; image.color = curColor;
放在while循环之后来解决此问题.
- 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 callStartCoroutine(FadeIn());
and putyield 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.
这篇关于如何在Unity中淡化UI图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!