- Home /
Why is the alpha on my UI Image not decreasing properly?
I've been at this for an hour now and I'm starting to lose my mind.
trying to make a simple blood overlay that is set active by an outside object, that reduces in alpha until its at 0 alpha, at which point it disables itself. Instead, it seems to only do two states for the alpha: fully on, or fully off. It disables and enables like it should, and even seems to detect when the Alpha should be 0 to turn itself off, but it doesn't do a proper fade-out.
Here's my code
public float alphaReduce=1f;
public Image myImage;
void OnEnable()
{
Color c = myImage.color;
c.a = 255;
myImage.color = c;
}
void Update () {
Color c = myImage.color;
c.a =c.a - alphaReduce;
myImage.color = c;
if (myImage.color.a <= 0) gameObject.SetActive(false);
}
Any help is appreciated.
Answer by fafase · Mar 30, 2019 at 09:40 AM
You are decreasing value without considering the performance of the computer.
float alphaReduce = 1f;
void Update () {
Color c = myImage.color;
c.a =c.a - alphaReduce * Time.deltaTime;
myImage.color = c;
if (myImage.color.a <= 0) gameObject.SetActive(false);
}
this will take 1s to complete if c.a is 1.
Answer by mchts · Mar 30, 2019 at 08:00 AM
Remember that Unity's build in Color takes r,g,b,a 0 to 1. I wrote sth like this:
public class Fade : MonoBehaviour {
public Image myImage;
public Color fadeColor; //you could arrange fade color from inspector too i assigned it manually here
void Start () {
//this line here is unnecessary if you assign fadeColor from inspector
fadeColor = new Color(myImage.color.r, myImage.color.g, myImage.color.b, 0f);
}
void Update () {
myImage.color = Color.Lerp(myImage.color, fadeColor, Time.deltaTime);
if (myImage.color.a < 0.02) { //having a threshold is a better option
gameObject.SetActive(false);
}
}
}
You are misusing Lerp in this context. The parameter you are passing are more appropriate for $$anonymous$$oveTowards method.
Color.Lerp(start, end, rate)
actually, since only the alpha is processed, $$anonymous$$athf.Lerp would be better. But then you need to control the rate so it reaches 1 to fulfil the interpolation.
So either:
Color c = myImage.color;
c.a = $$anonymous$$athf.$$anonymous$$oveTowards(c.a, 0f, step * Time.deltaTime);
myImage.color = c;
or:
elapsedTime += Time.deltaTime;
c.a = $$anonymous$$athf.Lerp(1f, 0f, elapsedTime / speed);
myImage.color = c;
For just changing alpha value your approach is more suitable for sure, but like i stated in the comment section i used Color.Lerp in terms of final color might be different than initial image color.
$$anonymous$$y point was not necessarily about the Color or $$anonymous$$athf but more about the fact you are misusing the parameters. What you're doing with Lerp is creating a limit process where the movement will never reach the destination. To hack that issue, you add the 0.02 check. You need to get your rate to reach 1 to use Lerp probably.