Unity3D游戏场景

场景类 Scene

- 获取当前活动场景

Scene scene = SceneManager.GetActiveScene();

- 场景名称

Debug.Log(scene.name);

- 是否加载

Debug.Log(scene.isLoaded);

- 场景路径

Debug.Log(scene.path);

- 场景索引

Debug.Log(scene.buildIndex);

- 获取场景内物体数量

GameObject[] objs = scene.GetRootGameObjects();
Debug.Log(objs.Length);

场景管理类 SceneManager

- 创建场景

SceneManager.CreateScene("NewScene");

- 加载场景(同步/异步)

  1. 同步加载场景

    SceneManager.LoadSceneAsync(“Scene2”,LoadSceneMode.Additive);

  2. 异步加载场景 协程

实例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public class SceneTest : MonoBehaviour
{
float timer = 0;
AsyncOperation operation;

// Start is called before the first frame update
void Start()
{
//异步加载场景 协程
StartCoroutine(LoadScene());
}

IEnumerator LoadScene()
{
operation = SceneManager.LoadSceneAsync("Scene2",LoadSceneMode.Additive);
//场景是否立即激活
operation.allowSceneActivation = false;
yield return operation;
}

// Update is called once per frame
void Update()
{
Debug.Log(operation.progress);
timer += Time.deltaTime;
if (timer > 5)
{
//5秒后激活加载的场景
operation.allowSceneActivation = true;
}
}
}