I am looking for the best way to fade into and out of a UI elements alpha level.
I am trying to effect just the alpha level on the color field of the Image component and am having quite lot of trouble with it.
Before anyone mentions it, I know I am doing it wrong, I am looking for the correct way to do this.
public void FadeIn (Image fadeObject)
{
fadeObject = Color.Lerp(0, 255, Time.deltaTime);
}
Color.Lerp lerps colors. you’re passing in integer values of 0 to 255.
Image has a property for its base color, Image.color.
Pull that value, lerp the alpha on it, and set it back to the Image.
Oh, and you’ll probably want something like SmoothDamp, I think I’ve seen you in a thread where it was explained to you what lerp is, and that it may not actually be the best for this type of stuff:
This is being done for a UI object, and I am calling it as a public void, so I cannot use the Update function.
Not sure why update can’t be used. But ok.
Start a coroutine, use that instead.
Get a tween engine, like iTween or HOTween, use that instead.
With the lerp the end number is the percentage of progress made using 0 - 1. You need to change that Time.deltaTime to something like this:
Float prog;
prog += Time.deltaTime;
Then you use the prog as the third value.
I have never even touched coroutines before and I am having trouble understanding the Unity documentation on it(Here).
All I need to be able to do is make this run properly.
public void fadeIn(CanvasGroup fadeObject)
{
fadeObject.alpha = Mathf.Lerp(fadeObject.alpha, 1, Time.deltaTime);
}
something like this:
float progress = 0.0f;
bool fadeIn = true;
void Update(){
if(fadeIn){
progress += Time.deltaTime;
if(progress >= 1.0f){
progress = 1.0f;
fadeIn = false;
}
fadeObject.alpha = Mathf.Lerp(0.0f, 1.0f, progress);
}
}
If you want to use InvokeRepeating then you can do something this:
float progress = 0.0f;
void Start(){
InvokeRepeating("FadeIn", 0.05f, 20);
}
void FadeIn(){
progress += 0.05f;
fadeObject.alpha = Mathf.Lerp(0.0f, 1.0f, progress);
}
if you are lerping between 0 and 1 you don’t really need the lerp function though as you can just set the alpha to the progress variable.