Unity 使用多场景管理API加载卸载场景
创建一个sceneLoad场景在场景上挂载SceneLoader.cs, _load_scene_name 填scene1,
创建scene1和scene2并挂载SwitchScene.cs,并将scene1的SwitchScene.cs的_next_scene_name填scene2,
scene2的SwitchScene.cs的_next_scene_name填scene1
SceneLoader.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class SceneLoader : MonoBehaviour
{
public string _load_scene_name;
// Start is called before the first frame update
void Start()
{
SceneManager.LoadScene(_load_scene_name,LoadSceneMode.Additive);
}
}
SwitchScene.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class SwitchScene : MonoBehaviour
{
public string _next_scene_name;
void OnEnable()
{
// 添加场景加载委托
SceneManager.sceneLoaded += OnSceneLoaded;
}
void OnSceneLoaded(Scene scene,LoadSceneMode mode)
{
SceneManager.SetActiveScene(SceneManager.GetSceneByName(scene.name)); // 这里不设置的话 SceneManager.GetActiveScene() 会取不到场景
Debug.Log("SceneName = " + scene.name);
Debug.Log("ActiveSceneName = " + SceneManager.GetActiveScene().name);
}
void OnDisable()
{
// 移除场景委托
SceneManager.sceneLoaded -= OnSceneLoaded;
}
public void GoToScene()
{
// 卸载当前场景
SceneManager.UnloadSceneAsync(SceneManager.GetSceneByName(SceneManager.GetActiveScene().name));
// 加载下一个场景
SceneManager.LoadScene(_next_scene_name, LoadSceneMode.Additive);
}
}