一、在相机下新建一个Canvas,添加Image 和CanvasGroup 组件
二、通过代码控制CanvasGroup 组件中Alpha值
以下函数要放在Update中执行。
第一种写法(判断条件为Alpha 0-1的值)
private float Alpha;
private float AlphaSpeed = 1.5f; //Alpha值渐变的时间
/// <summary>
/// 控制Alpha值增加
/// </summary>
/// <param name="_mask"></param>
public void AlphaControl(GameObject _mask)
{
if (_mask != null)
{
_mask.SetActive(true);
Alpha += Time.deltaTime * 1 / AlphaSpeed;
_mask.GetComponent<CanvasGroup>().alpha = Alpha;
if (Alpha >= 0.95f) playAnimation = PlayAnimation.EnterGame;
}
}
第二种写法(判断条件为持续时间)
/// <summary>
/// 屏幕遮罩
/// </summary>
public CanvasGroup screenMask;
/// <summary>
/// 遮罩的Alpha
/// </summary>
private float maskAlpha;
/// <summary>
/// 遮罩的Alpha持续时间
/// </summary>
private float maskAlphaDuration = 5f;
/// <summary>
/// 游戏结束画面逐渐变黑并退出游戏场景
/// </summary>
private void GameOver()
{
if (isGameOver)
{
maskAlpha += Time.deltaTime;
screenMask.alpha = maskAlpha / maskAlphaDuration;
if (maskAlpha >= maskAlphaDuration)
{
maskAlpha = 0;
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying = false;
#else
Application.Quit();
#endif
}
}
}
三、 通过Image组件实现相机的遮罩效果
注意:如果CanvasGroup和Image同时存在,需将CanvasGroup的Alpha值改为1,再进行控制Image的Alpha值。
/// <summary>
/// 屏幕遮罩
/// </summary>
public Image screenMask;
/// <summary>
/// 遮罩的Alpha
/// </summary>
private float maskAlpha;
/// <summary>
/// 遮罩的Alpha持续时间
/// </summary>
private float maskAlphaDuration = 5f;
/// <summary>
/// 游戏结束画面逐渐变黑并退出游戏场景
/// </summary>
private void GameOver()
{
if (isGameOver)
{
var r = screenMask.color.r;
var g = screenMask.color.g;
var b = screenMask.color.b;
maskAlpha += Time.deltaTime;
screenMask.color = new Color(r, g, b, maskAlpha / maskAlphaDuration);
if (maskAlpha >= maskAlphaDuration)
{
maskAlpha = 0;
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying = false;
#else
Application.Quit();
#endif
}
}
}
|