切换场景的淡入淡出效果

通过改变图片的透明度来控制场景的淡入和淡出
一、首先在A和B场景中各添加Image使其铺满屏幕,并且添加CanvasGroup组件
并且Image颜色设置为黑色,A场景Alpha设置为0,B场景Alpha设置为1
二、在AB两个场景中各创建空物体,添加脚本,代码如下

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
/// 
/// 从A场景切换到B场景
/// 默认A场景Alpha为0,B场景Alpha为1
/// 
public class ChangeScenes : MonoBehaviour {

    //遮挡摄像机的UI
    public CanvasGroup m_CanvasGroup;

    //AB场景名字
    string AsceneName = "1";
    string BsceneName = "2";

    //淡出速度
    float FadeOutSpeed = 0.008f;
    //淡入速度
    float FadeInSpeed = 0.004f;

     void Start()
     {
         //B场景自动执行淡入效果
         if (SceneManager.GetActiveScene().name == BsceneName)
         {
             StartCoroutine(SceneFadeIn());
         }
     }

     void Update()
     {
         //判断是当前场景,执行淡出效果
         if (SceneManager.GetActiveScene().name == AsceneName)
         {
             //随意给了个条件(按需求调用)
             if (Input.GetKeyDown(KeyCode.Space))
             {
                 StartCoroutine(SceneFadeOut());
             }
         }
     }

    /// 
    /// 场景淡出
    /// 
    /// 
     IEnumerator SceneFadeOut()
     {
         while (m_CanvasGroup.alpha < 1)
         {
             m_CanvasGroup.alpha += FadeOutSpeed;
             yield return new WaitForSeconds(Time.deltaTime);
         }
         SceneManager.LoadScene(BsceneName);
     }

    /// 
    /// 场景淡入
    /// 
    /// 
     IEnumerator SceneFadeIn()
     {
         while (m_CanvasGroup.alpha > 0)
         {
             m_CanvasGroup.alpha -= FadeInSpeed;
             yield return new WaitForSeconds(Time.deltaTime);
         }
     }
}

你可能感兴趣的:(切换场景的淡入淡出效果)