讲解关于协程的知识,通过协程加载场景,在场景中创建一个用于加载场景的门户
Portal
- using System.Collections;
- using System.Collections.Generic;
- using Unity.VisualScripting;
- using UnityEngine;
- using UnityEngine.SceneManagement;
-
- namespace RPG.SceneMangement
- {
- //// Portal 类用于在玩家进入触发器时异步加载新场景
- public class Portal : MonoBehaviour
- {
- [SerializeField] int sceneToLoad = 1;
- float times = 0;
- // 当触发器碰撞到其他对象时调用
- private void OnTriggerEnter(Collider other)
- {
-
- // 如果碰撞的对象是玩家
- if (other.tag == "Player")
- {
- print("开始加载场景");
- times += Time.deltaTime;
- StartCoroutine(Transition());
- }
-
- }
-
- private IEnumerator Transition()
- {
-
- DontDestroyOnLoad(gameObject);
- yield return SceneManager.LoadSceneAsync(sceneToLoad);
- print(times + "秒后加载完成");
- Destroy(gameObject);
- }
-
-
- }
- }
-
复制代码
|