简体   繁体   English

Unity场景到场景间对象间通信:如何?

[英]Unity Scene-to-Scene inter-object communication: HOW?

Unity has an ability to have one scene act as a host for other sub-scenes, additively and asynchronously loaded, later in the game. 在游戏的后期,Unity可以让一个场景作为其他子场景的主机,以增补和异步方式加载。

What are the ways an object in a host scene can know of and be sure of communicating with an object in an additively loaded sub-scene? 主机场景中的对象可以通过什么方式知道并确保与添加加载的子场景中的对象通信?

And the inverse, how can an object in the additively loaded scene communicate with an object in its host scene? 反之,加性加载场景中的对象如何与其宿主场景中的对象通信?

First, in Unity's UnityEngine.SceneManagement package, you can use SceneManager.GetSceneByName("scene name here") which returns Scene . 首先,在Unity的UnityEngine.SceneManagement包中,您可以使用SceneManager.GetSceneByName("scene name here") ,该返回Scene If the scene is null, then the scene is not yet loaded. 如果场景为空,则尚未加载场景。 If it is, you can use isLoaded to check if it is loaded, SceneManager . 如果是,则可以使用isLoaded来检查是否已加载SceneManager You can either use Find after that, but I do not recommend this as it is a slow process. 之后,您可以使用“ Find ,但是我不建议您这样做,因为这是一个缓慢的过程。

Second, if the object you are referring to is a GameObject and you need a component attached to it, you can use Singleton pattern so you can access the only instance of the script. 其次,如果您要引用的对象是GameObject并且需要附加组件,则可以使用Singleton模式,以便可以访问脚本的唯一实例。 You can just assign instance = null under OnDestroy so that the instance will be gone when the scene is unloaded. 您可以在OnDestroy下分配instance = null ,以便在卸载场景时实例消失。 This option is viable if the script is in the host scene since, I assume, it is not unloaded/destroyed. 如果脚本位于宿主场景中,则此选项是可行的,因为我认为脚本没有卸载/销毁。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM