場景切換前必須要將場景拖動到Build中
同步加載場景
using System.Collections;
using System.Collections.Generic;
//using UnityEditor.SearchService;
using UnityEngine;
// 場景管理 需要導入該類
using UnityEngine.SceneManagement;public class c3 : MonoBehaviour
{// Start is called before the first frame updatevoid Start(){// 獲取當前場景Scene scene1 = SceneManager.GetActiveScene();Debug.Log(scene1.name);// 場景是否加載完成Debug.Log(scene1.isLoaded);// 場景路徑Debug.Log(scene1.path);// 場景中最外層的游戲物體GameObject[] gameObjects = scene1.GetRootGameObjects();Debug.Log(gameObjects.Length); // 看場景中的數量// 切換場景// 根據序號//SceneManager.LoadScene(1);// 根據場景名//SceneManager.LoadScene("Scene2");// 替換場景//SceneManager.LoadScene("Scene2", LoadSceneMode.Single);// 融合場景//SceneManager.LoadScene("Scene2", LoadSceneMode.Additive);// 創建新場景}// Update is called once per framevoid Update(){}
}
異步加載場景
using System.Collections;
using System.Collections.Generic;
//using UnityEditor.SearchService;
using UnityEngine;
// 場景管理 需要導入該類
using UnityEngine.SceneManagement;public class c3 : MonoBehaviour
{// 聲明 AsyncOperation類型的 返回值AsyncOperation operation;void Start(){// 調用協程StartCoroutine(loadScene());}// 計時器 5秒后再跳轉float t1 = 0;// 協程IEnumerator loadScene(){operation = SceneManager.LoadSceneAsync(1);// 加載后 可以不要自動跳轉operation.allowSceneActivation = false;yield return operation;}void Update(){// 獲取加載進度 0-0.9// Debug.Log(operation.progress);t1 += Time.deltaTime;// 如果到5秒,則跳轉場景if (t1 >=5){operation.allowSceneActivation = true;}}
}