5.1 场景(Scene)的概念
场景是 Unity 中组织和编辑游戏内容的基本单位。一个场景可以包含:
- 游戏物体(GameObject)
- 灯光和摄像机
- UI 元素
- 音频源
- 导航网格
游戏由多个场景组成,常用于:
5.2 场景管理
场景操作 API
1 2 3 4 5 6 7 8
| using UnityEngine.SceneManagement;
Scene currentScene = SceneManager.GetActiveScene(); Debug.Log($"场景名称:{currentScene.name}"); Debug.Log($"场景索引:{currentScene.buildIndex}"); Debug.Log($"是否已加载:{currentScene.isLoaded}"); Debug.Log($"根物体数量:{currentScene.rootCount}");
|
加载场景
1 2 3 4 5 6 7 8 9 10 11 12 13
| SceneManager.LoadScene("Level2");
SceneManager.LoadScene(1);
AsyncOperation operation = SceneManager.LoadSceneAsync("Level2"); operation.allowSceneActivation = false;
yield return new WaitUntil(() => operation.progress >= 0.9f); operation.allowSceneActivation = true;
|
场景需要在 File → Build Settings 中添加到 Build 列表才能通过索引加载。
多场景加载
1 2 3 4 5
| SceneManager.LoadScene("UI_Overlay", LoadSceneMode.Additive);
SceneManager.UnloadSceneAsync("UI_Overlay");
|
5.3 坐标系统
Unity 使用左手坐标系:
- X 轴:向右
- Y 轴:向上
- Z 轴:向前(屏幕内)
世界坐标 vs 本地坐标
1 2 3 4 5 6 7 8 9 10 11
| Vector3 worldPos = transform.position;
Vector3 localPos = transform.localPosition;
Vector3 localFromWorld = transform.InverseTransformPoint(worldPoint);
Vector3 worldFromLocal = transform.TransformPoint(localPoint);
|
5.4 Vector3 常用操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| Vector3 forward = Vector3.forward; Vector3 up = Vector3.up; Vector3 right = Vector3.right;
float dist = Vector3.Distance(posA, posB);
Vector3 dir = (targetPos - transform.position).normalized;
Vector3 middle = Vector3.Lerp(posA, posB, 0.5f); Vector3 smooth = Vector3.Lerp(current, target, Time.deltaTime * 2f);
float dot = Vector3.Dot(transform.forward, direction);
Vector3 cross = Vector3.Cross(transform.forward, direction);
|
5.5 四元数与旋转
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| Quaternion rotation = Quaternion.Euler(0, 90, 0);
transform.rotation = Quaternion.LookRotation(direction);
transform.rotation = Quaternion.Slerp( transform.rotation, targetRotation, Time.deltaTime * 5f );
Quaternion delta = Quaternion.FromToRotation(Vector3.up, hit.normal);
|
5.6 本章小结
- 场景是游戏内容的组织单位,通过
SceneManager 加载/卸载
- Unity 使用左手坐标系,Y 轴向上
- 理解世界坐标与本地坐标的区别
- Vector3 提供丰富的向量运算方法
- 旋转操作使用 Quaternion(四元数)避免万向锁
练习题
- 创建两个场景 Scene1 和 Scene2,实现按空格键切换
- 在脚本中使用
Vector3.Lerp 让物体平滑移动到目标位置
- 练习
TransformPoint 和 InverseTransformPoint,理解坐标转换
- 使用
Quaternion.Slerp 实现炮塔平滑转向目标