摘自《Unity游戏设计与实现/南梦宫一线程序员的开发实例》
using UnityEngine;
class FadeInOutManager : MonoBehaviour
{
// 黑幕对象
public GUITexture m_fadeInOutObject = null;
//==============================================================================================
/// 当前Alpha值
private float m_currentAlpha = 1.0f;
/// 目标Alpha值
private float m_destinationAlpha = 0.0f;
/// 开始的时间
private float m_beginTime = 0.0f;
/// 结束的时间
private float m_endTime = 0.0f;
private bool m_isFading = false;
private void Start()
{
m_fadeInOutObject.color = new Color( 0.0f, 0.0f, 0.0f, m_currentAlpha );
m_fadeInOutObject.enabled = true;
}
private void Update()
{
if ( m_isFading )
{
if ( Time.time >= m_endTime )
{
m_fadeInOutObject.color = new Color( 0.0f, 0.0f, 0.0f, m_currentAlpha = m_destinationAlpha );
// 如果Alpha为0,隐藏对象
if ( m_destinationAlpha < 0.25f) // 由于它是浮点数,因此请勿设置== 0.0f
{
m_fadeInOutObject.enabled = false;
}
m_isFading = false;
}
else
{
// 進行度 (0.0~1.0) // 反向差值函数
float ratio = Mathf.InverseLerp( m_beginTime, m_endTime, Time.time );
// 修改Alpha值
m_fadeInOutObject.color = new Color( 0.0f, 0.0f, 0.0f,
Mathf.Lerp( m_currentAlpha, m_destinationAlpha, ratio ) );
}
}
}
//==============================================================================================
// 公開メソッド
/// <summary>フェードアウトを行う</summary>
public void fadeOut( float duration )
{
fadeTo( 1.0f, duration );
}
/// <summary>フェードインを行う</summary>
public void fadeIn( float duration )
{
fadeTo( 0.0f, duration );
}
/// <summary>フェードを行う</summary>
public void fadeTo( float destinationAlpha, float duration )
{
m_destinationAlpha = destinationAlpha;
m_beginTime = Time.time;
m_endTime = m_beginTime + duration;
m_isFading = true;
// GUITexture を有効にする
m_fadeInOutObject.enabled = true;
}
/// <summary>フェード中かどうかを返す</summary>
public bool isFading()
{
return m_isFading;
}
}
调用:
m_manager.fadeIn( m_duration );
m_manager.fadeOut( m_duration );