using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class FadeImageInOut : MonoBehaviour {
public Image m_targetImage;
public float m_fadeDuration = 1f;
public float m_stayDuration = 2f;
public AnimationCurve m_smoothCurve = new AnimationCurve( new Keyframe[] { new Keyframe( 0f, 0f ), new Keyframe( 1f, 1f ) } );
private float m_timerCurrent;
private readonly WaitForSeconds m_skipFrame = new WaitForSeconds( 0.01f );
void Start()
{
if (m_targetImage != null)
{
StartCoroutine( FadeInOut() );
}
else
{
Debug.LogWarning( "Please set TargetImage in the Inspector before trying this." );
}
}
private IEnumerator FadeInOut()
{
float start = 0f;
float end = 1f;
yield return StartCoroutine( Fade( start, end ) ); // Fade in.
yield return new WaitForSeconds( m_stayDuration ); // Stay
yield return StartCoroutine( Fade( end, start ) ); // Fade out.
}
private IEnumerator Fade(float start, float end)
{
m_timerCurrent = 0f;
while (m_timerCurrent <= m_fadeDuration)
{
m_timerCurrent += Time.deltaTime;
Color c = m_targetImage.color;
m_targetImage.color = new Color( c.r, c.g, c.b, Mathf.Lerp( start, end, m_smoothCurve.Evaluate( m_timerCurrent / m_fadeDuration ) ) );
yield return m_skipFrame;
}
}
}
I noticed this is a question from 2015. I hope it helps regardless!
If you’re reading this OP and it did help, then accepting the answer would be much appreciated!
You can most definitely fade UI images, using the alpha value of the color property. I don’t know the LeanTween library though; check if it has the option to fade colors (it seems likely that it should).
If not, nothing wrong with a little coroutine to do the fade yourself. Also, be aware that a UI button by default has a background image and a text as child - you will have to fade both out simultaneously if both are present.