Lean Tween
Unity
Dented Pixel’s Lean Tween asset for the Unity Game engine is fantastic and has a number of functions to manipulate the alpha property of various components. The Unity canvas components are supported to a large degree and today I wanted to draw attention to the Canvas Group component.
Because it’s not fun to implement fading on each button, button text and image of your canvas or panel Unity has a component called Canvas Group. You make this Canvas Group component the parent of a section of your UI, or the whole things and use its handy dandy Alpha float property to fade all the Canvas group’s children at once.
Lean Tween has a built in method to achieve this LeanTween.alphaCanvas(), which takes a Canvas Group component as its object.
Create a private variable to get a reference to your Canvas Group
public float durationOfFadeIn; private CanvasGroup _canvasGroup; void Start() { _canvasGroup = GetComponent<CanvasGroup>(); FadeIn(); }
Use LeanTween's alphaCanvas to fade the referenced Canvas Group
void FadeIn() { LeanTween.alphaCanvas(_canvasGroup, 1f, durationOfFadeIn); }
How it Works
- In the first section we set a public variable to allow inspector input of a float controlling how long the fade in of your Canvas Group and all its elements will last.
- We create a private variable that will hold our reference to you Canvas Group object.
- In the start method we pluck the Canvas Group object attached to this MonoBehaviour using GetComponent<>
- Call a custom function FadeIn() which contains the Lean Tween function alphaCanvas
- This is optional you could also call LeanTween.alphaCanvas in the Start() method.
- LeanTween.alphaCanvas() takes three properties, the Canvas Group reference, the alpha value you want to tween towards and the time you’d like that tween to take.