Unity:场景管理
场景类头文件 using UnityEngine.SceneManagement;
AsyncOperation operation; //异步加载类对象
//1.创建场景,运行结束会销毁
Scene scene = SceneManager.CreateScene("001");
//2.加载场景 LoadSceneMode是加载模式,默认Single模式
SceneManager.LoadScene("002",LoadSceneMode.Additive);
//3.拿到场景
Scene scene2 = SceneManager.GetActiveScene(); //拿到当前活跃的场景(挂载该脚本的场景)
Scene scene3 = SceneManager.GetSceneByName("002");
Scene scene4 = SceneManager.GetSceneByName("003"); // × 返回null,没有加载的场景是拿不到的
}
//4.卸载场景
SceneManager.UnloadSceneAsync("002");
5.异步加载场景
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 private AsyncOperation operation; //场景加载类对象 2 3 void Start () { 4 StartCoroutine(LoadScene()); 5 } 6 7 IEnumerator LoadScene() 8 { 9 //异步加载场景 10 operation = SceneManager.LoadSceneAsync(0); 11 yield return operation; 12 }
6.场景淡入淡出
创建一张Image图片,填充屏幕,脚本挂载Canvas上
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 using System.Collections; 2 using System.Collections.Generic; 3 using UnityEngine; 4 using UnityEngine.UI; 5 using UnityEngine.SceneManagement; 6 7 public class LoadScene : MonoBehaviour 8 { 9 public float fadeSpeed; 10 public Image image; 11 float colorAlpha; 12 bool isQuit; 13 void Start() 14 { 15 image.color = Color.clear; 16 DontDestroyOnLoad(gameObject); //脚本所挂载物体过场不销毁 17 } 18 private void Update() 19 { 20 if (!isQuit) 21 QuitScene(); 22 else 23 EnterScene(); 24 } 25 void QuitScene() 26 { 27 colorAlpha = Mathf.Lerp(colorAlpha, 1, Time.deltaTime * fadeSpeed); //渐黑 28 if (colorAlpha > 0.95f) 29 colorAlpha = 1; 30 image.color = new Color(image.color.r, image.color.g, image.color.b, colorAlpha); 31 if (colorAlpha == 1) 32 { 33 isQuit = true; 34 SceneManager.LoadScene(0); 35 } 36 } 37 void EnterScene() 38 { 39 colorAlpha = Mathf.Lerp(colorAlpha, 0, Time.deltaTime * fadeSpeed); //渐白 40 if (colorAlpha < 0.05f) 41 colorAlpha = 0; 42 image.color = new Color(image.color.r, image.color.g, image.color.b, colorAlpha); 43 if (colorAlpha==0) 44 Destroy(gameObject); 45 } 46 }