- Home /
how do i Mathf.lerp the SpriteRenderer.alpha?
var colorAlpha = new Color32(255, 255, 255, 255);
colorAlpha.a = (byte)Mathf.Lerp(255, 0, 1.5f * Time.deltaTime);
ChestRender.color = colorAlpha;
I'm trying to fade a image when it's clicked... Is there a way to mathf.lerp the spriterenderer alpha?
Answer by xibanya · Dec 30, 2019 at 02:07 AM
this'll do the trick.
public IEnumerator SpriteFade(
SpriteRenderer sr,
float endValue,
float duration)
{
float elapsedTime = 0;
float startValue = sr.color.a;
while (elapsedTime < duration)
{
elapsedTime += Time.deltaTime;
float newAlpha = Mathf.Lerp(startValue, endValue, elapsedTime / duration);
sr.color = new Color(sr.color.r, sr.color.g, sr.color.b, newAlpha);
yield return null;
}
}
Remember to think of Lerp as having the first argument at 0 and the second argument at 100%. The third argument is where between 0 and 100% the value should fall. (You can also put an argument that's higher than 100% proportionally, but that's not going to be needed here.) elapsedTime / duration
will get you the percentage of time completion of the blend. Since elapsedTime
won't be higher than duration
(since the while loop will stop if that happens) we can be confident that it will be between 0 and 1, making it ideal for blending between the two values.
Note that Unity's native Color
struct uses color values between 0 and 1 rather than 0 and 255. I recommend going with Unity's native Color struct unless there's something specific you're trying to achieve with Color32 instead.
I was going for the color32 because it gives a value of 255. not 0 to 1 but this works great in my scene. Thanks!
Your answer
Follow this Question
Related Questions
Finding all sprite renderers in the scene and tell them to change color 1 Answer
How to change the alpha element of particles/additive color? 1 Answer
Using Color's alpha channel with value greater than one provides odd result 1 Answer
How to get Sprite color palette 1 Answer
Shader that does per Vert alpha with co 0 Answers