Unit-demo ✨ makes the UI screen “boling” “Boling” flicker

preface

A little knowledge every day, today to do a UI element running lamp effect, quick look!

Recently, I wanted to make UI components (images, fonts, etc.) flicker. I thought of the CanvasGroup component. I used code to control the alpha in the CanvasGroup component to achieve the flicker effect of UI components.

Control the UI component transparency changes with the following code, the first value is the initial UI transparency, the second value is the target transparency to achieve, and the last value is the rate at which the transparency changes.

Mathf.Lerp(canvasGroup.alpha, alpha, alphaSpeed * Time.deltaTime);
Copy the code

The effect is as follows:Add the CanvasGrounp component to the Panel, then hang the script and use it

The script code is as follows:

 public class First : MonoBehaviour
    {
        private Text tips;// The blinking Text component
        private CanvasGroup canvasGroup;
        private float alphaSpeed = 5f;// Flash speed
        private float alpha = 0.2 f;// Minimum transparency
        private bool isShow = true;// To control the content of the flicker

        void Awake()
        {
            tips = transform.Find("Tips").GetComponent<Text>();
            canvasGroup = tips.transform.GetComponent<CanvasGroup>();
        }
        private void Update()
        {
            if (isShow)
            {
                if(canvasGroup.alpha ! = alpha) { canvasGroup.alpha = Mathf.Lerp(canvasGroup.alpha, alpha, alphaSpeed * Time.deltaTime);if (Mathf.Abs(canvasGroup.alpha - alpha) <= 0.01)
                    {
                        canvasGroup.alpha = alpha;
                        isShow = false; }}}else
            {
                if(canvasGroup.alpha ! =1)
                {
                    canvasGroup.alpha = Mathf.Lerp(canvasGroup.alpha, 1, alphaSpeed * Time.deltaTime);
                    if (Mathf.Abs(1 - canvasGroup.alpha) <= 0.01)
                    {
                        canvasGroup.alpha = 1;
                        isShow = true; }}}}Copy the code

conclusion

Use the CanvasGroup component to adjust the transparency of the UI, so that a UI element will flicker, define a bool to make it flicker repeatedly, and mount the script to the element that needs to flicker! This can meet our needs!! Did you learn today?