Hiệu ứng chuyển cảnh (Screen Transition)
C# Code
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using System.Collections;
public class ScreenFader : MonoBehaviour
{
public static ScreenFader Instance;
public Image fadeImage;
public float fadeSpeed = 1.5f;
void Awake()
{
if (Instance == null) {
Instance = this;
DontDestroyOnLoad(gameObject);
} else {
Destroy(gameObject);
}
}
public void FadeToScene(string sceneName)
{
StartCoroutine(FadeOutAndLoad(sceneName));
}
IEnumerator FadeOutAndLoad(string sceneName)
{
yield return StartCoroutine(Fade(1f)); // Fade Out
SceneManager.LoadScene(sceneName);
yield return StartCoroutine(Fade(0f)); // Fade In
}
IEnumerator Fade(float targetAlpha)
{
Color currentColor = fadeImage.color;
float startAlpha = currentColor.a;
float timer = 0f;
while (timer < 1f)
{
timer += Time.deltaTime * fadeSpeed;
currentColor.a = Mathf.Lerp(startAlpha, targetAlpha, timer);
fadeImage.color = currentColor;
yield return null;
}
currentColor.a = targetAlpha;
fadeImage.color = currentColor;
}
}Một hệ thống đơn giản để tạo hiệu ứng chuyển cảnh, ví dụ như làm mờ dần sang màu đen (Fade to Black) khi tải scene mới.