46 lines
1.5 KiB
C#
46 lines
1.5 KiB
C#
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
using UnityEngine.SceneManagement;
|
|
|
|
/// <summary>
|
|
/// 用于管理场景跳转的单例
|
|
/// </summary>
|
|
public class TransitionManager : Singleton<TransitionManager>
|
|
{
|
|
public CanvasGroup fadeCanvasGroup;
|
|
public float fadeDuration=0.3f;
|
|
private bool isFade;
|
|
|
|
public void Transition(string from, string to)
|
|
{
|
|
if (!isFade) StartCoroutine(TransitionToScene(from, to));
|
|
}
|
|
private IEnumerator TransitionToScene(string from, string to)
|
|
{
|
|
yield return Fade(1);
|
|
//等待场景卸载完成后继续
|
|
yield return SceneManager.UnloadSceneAsync(from);
|
|
//等待场景加载完成后继续
|
|
yield return SceneManager.LoadSceneAsync(to, LoadSceneMode.Additive);
|
|
//设置新场景为激活场景
|
|
Scene newScene = SceneManager.GetSceneByName(to);
|
|
SceneManager.SetActiveScene(newScene);
|
|
yield return Fade(0);
|
|
}
|
|
private IEnumerator Fade(float targetAlpha)
|
|
{
|
|
//where are you now!
|
|
isFade = true;
|
|
fadeCanvasGroup.blocksRaycasts = true;
|
|
float speed = Mathf.Abs(fadeCanvasGroup.alpha - targetAlpha) / fadeDuration;
|
|
while (!Mathf.Approximately(fadeCanvasGroup.alpha, targetAlpha))
|
|
{
|
|
fadeCanvasGroup.alpha = Mathf.MoveTowards(fadeCanvasGroup.alpha, targetAlpha, speed * Time.deltaTime);
|
|
yield return null;
|
|
}
|
|
fadeCanvasGroup.blocksRaycasts = false;
|
|
isFade = false;
|
|
}
|
|
}
|