1 回答
TA贡献1844条经验 获得超8个赞
Start您可以为SceneManager.sceneLoaded添加一个侦听器,而不是在其中执行此操作
仅在加载初始场景时才执行这些操作,您可以使用它SceneManager.GetActiveScene()来存储并稍后将初始场景与加载的场景进行比较。
// Store the scene that should trigger start
private Scene scene;
private void Awake()
{
// It is save to remove listeners even if they
// didn't exist so far.
// This makes sure it is added only once
SceneManager.sceneLoaded -= OnsceneLoaded;
// Add the listener to be called when a scene is loaded
SceneManager.sceneLoaded += OnSceneLoaded;
DontDestroyOnLoad(gameObject);
// Store the creating scene as the scene to trigger start
scene = SceneManager.GetActiveScene();
}
private void OnDestroy()
{
// Always clean up your listeners when not needed anymore
SceneManager.sceneLoaded -= OnSceneLoaded;
}
// Listener for sceneLoaded
private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
{
// return if not the start calling scene
if(!string.Equals(scene.path, this.scene.path) return;
Debug.Log("Re-Initializing", this);
// do your "Start" stuff here
}
Afaik /我如何理解链接中的示例OnSceneLoaded也将在第一个场景中调用,只要您在之前添加回调Start(所以在Awakeor中OnEnable)。
注意我使用Scene.path s 而不是scene.name因为path它总是唯一的(由于操作系统文件系统),而name可能不是。
- 1 回答
- 0 关注
- 141 浏览
添加回答
举报
