I have a panel that changes the alpha over time when the player collides with a collider in the game, but it half works, it goes to random values every time so sometimes it will be full opaque and sometimes it will be at like 253 alpha, I want it to reach full opaque when the collide happens, here’s my script.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UIFadeIn : MonoBehaviour
{
public Panel Mypanel;
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.name == "Finish")
{
Collided();
}
}
private void Collided()
{
StartCoroutine(FadePanel(true));
}
IEnumerator FadePanel(bool fadepanel)
{
for (float i = 0; i <= 1; i += Time.deltaTime)
{
Mypanel.color = new Color(0, 0, 0, i);
yield return null;
}
}
}
Thanks in advance
If you debug Time.deltaTime, you’ll see an average value. Since 253/255 is about .9921, if adding Time.deltaTime pushes it above 1, your loop will exit, leaving it short for 255.
There are many ways to handle lerping a number from one value to another, and you can look those up. A simple fix would be to simply set the UI panel value to 1 alpha after the for loop, so when it kicks it out, it just knows it’s “close enough” that setting it to max isn’t a big deal.
But, this isn’t how I would handle it, it just should fix it with the code you have right now.
I would use an existing method or, as I do with most UI stuff, I would use a tween library such as LeanTween or Dotween.
Also, I’m pretty sure if Kurt pops in here, he has a good one for lerps.
1 Like
Allow me to pop in and offer my lerp / fading suggestions!
First, if you can just do it with an animation, DO THAT… no code to debug.
Fading, simple and easy:
https://discussions.unity.com/t/808656/5
Smoothing movement between any two particular values:
https://discussions.unity.com/t/812925/5
You have currentQuantity and desiredQuantity.
- only set desiredQuantity
- the code always moves currentQuantity towards desiredQuantity
- read currentQuantity for the smoothed value
Works for floats, Vectors, Colors, Quaternions, anything continuous or lerp-able.
The code: https://gist.github.com/kurtdekker/fb3c33ec6911a1d9bfcb23e9f62adac4
Another approach would be to use a tweening package line LeanTween, DOTween or iTween.
OR… as I said above, just make a simple canned animation… No code needed!
Though Kurt has given good reasons not to use a coroutine in his first link, if for some reason you wanted to use one it can be done something like this:
IEnumerator FadeIn () {
while (myItem.alpha < 1) {
myItem.alpha += 0.05f;
yield return new WaitForSeconds (0.00000001f); //The WaitForSeconds can be cached to avoid having to declare a new one every iteration
}
}
You can also just restart the corotuine after the wait to avoid using a while loop.
Ok I went with the animation, which I should have done right from the start, thank y’all