Tải và chuyển cảnh (SceneLoader)
C# Code
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using System.Collections;
public class SceneLoader : MonoBehaviour
{
public Slider loadingBar;
public GameObject loadingScreen;
// Tải một cảnh bằng tên của nó
public void LoadScene(string sceneName)
{
StartCoroutine(LoadSceneAsynchronously(sceneName));
}
private IEnumerator LoadSceneAsynchronously(string sceneName)
{
AsyncOperation operation = SceneManager.LoadSceneAsync(sceneName);
if (loadingScreen != null) loadingScreen.SetActive(true);
while (!operation.isDone)
{
// operation.progress có giá trị từ 0 đến 0.9
float progress = Mathf.Clamp01(operation.progress / 0.9f);
if (loadingBar != null) loadingBar.value = progress;
Debug.Log("Loading progress: " + (progress * 100f) + "%");
yield return null;
}
}
// Tải lại cảnh hiện tại
public void ReloadCurrentScene()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
}Một script quản lý việc chuyển cảnh trong Unity, bao gồm cả việc tải cảnh bất đồng bộ (asynchronously) với thanh tiến trình (loading bar).