
Lean Tween
Unity
There are several ways to fade a SpriteRenderer sprite using the Lean Tween library. You can use LeanTween.alpha, which almost always works but sometimes sets the alpha of the shared material tint rather than then SpriteRenderer.color property.
In those case, you can use LeanTween.value which takes the float value of the tween as a parameter on every frame of the tween. With this method you can tween any value in Unity, even those that Lean Tween does not have a built in method for. See the “how it works” section below the snippet.
Fade In with LeanTween.alpha
LeanTween.alpha(gameObject, 1f, 2f);
Fade In with LeanTween.value
LeanTween.value(gameObject, 1f, 0, 2f).setOnUpdate((float val)=> { SpriteRenderer sr = gameObject.GetComponent<SpriteRenderer>(); Color newColor = sr.color; newColor.a = val; sr.color = newColor; });
How it Works
- Calls LeanTween.Value with standard parameters (object, to value, from value, duration), chains the setOnUpdate function to the LeanTween call and passes in a lambda function.
- { start of lambda function
- Gets a reference to the object’s SpriteRenderer component and stores it in sr
- Creates a new Color and assigns the color of the SpriteRenderer in line 2, this essentially creates of copy of the color settings on your sprite.
- Changes the alpha parameter of the new color to be the tweened value, this value will increase or decrease every frame of the tween.
- Sets the new color back to the sprites color updating the sprite.
- End anonymous function and end LeanTween function call.