Search Unity

  1. We've closed the job boards. If you're looking for work, or looking to hire check out Unity Connect. You can see more information here.
    Dismiss Notice
  2. Unity 2017.3 has arrived! Read about it here.
    Dismiss Notice
  3. Want to see the most recent patch releases? Take a peek at the patch release page.
    Dismiss Notice

Simple UI animation Fade in \ Fade out C#

Discussion in 'Animation' started by giubbannetto, Nov 6, 2016.

  1. giubbannetto

    giubbannetto

    Joined:
    Oct 15, 2012
    Posts:
    2
    As title i have to make this animation on different UI images . I want two animations that make square images appear and disappear at button click. Can someone help me? Thank You.
     
  2. ryanreptoid

    ryanreptoid

    Joined:
    Aug 12, 2012
    Posts:
    70
    You can use coroutines to animate a fade in code, eg:

    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.UI;
    3. using System.Collections;
    4.  
    5. public class ImageFade : MonoBehaviour {
    6.  
    7.     // the image you want to fade, assign in inspector
    8.     public Image img;
    9.    
    10.     public void OnButtonClick()
    11.     {
    12.         // fades the image out when you click
    13.         StartCoroutine(FadeImage(true));
    14.     }
    15.  
    16.     IEnumerator FadeImage(bool fadeAway)
    17.     {
    18.         // fade from opaque to transparent
    19.         if (fadeAway)
    20.         {
    21.             // loop over 1 second backwards
    22.             for (float i = 1; i >= 0; i -= Time.deltaTime)
    23.             {
    24.                 // set color with i as alpha
    25.                 img.color = new Color(1, 1, 1, i);
    26.                 yield return null;
    27.             }
    28.         }
    29.         // fade from transparent to opaque
    30.         else
    31.         {
    32.             // loop over 1 second
    33.             for (float i = 0; i <= 1; i += Time.deltaTime)
    34.             {
    35.                 // set color with i as alpha
    36.                 img.color = new Color(1, 1, 1, i);
    37.                 yield return null;
    38.             }
    39.         }
    40.     }
    41. }
    42.  
    You can also create an Animator for your UI components and animate their fade, calling the animation in code whenever you want the fade to happen.
     
  3. giubbannetto

    giubbannetto

    Joined:
    Oct 15, 2012
    Posts:
    2
    Thank you. So i already have two animation and i put them in the animator, i know how to call it in the code but the problem is that i need a "idle" one that is full transparent or maybe disable image. I have a code that works but there are some animation problems.