本文介绍了是否启用Unity中另一个场景中存在的gameObject?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我通过当前场景中的脚本执行上述操作时,如何设置另一个场景中存在的gameObject true/false GameObject.SetActive(true);?

How do I set a gameObject true/false GameObject.SetActive(true); that is present in another scene while I do the above through a script from my current scene?

推荐答案

正如@Eddge所说,您无法从未加载的场景访问对象.场景对象实际上是在场景加载时创建的,因此之前无法访问它们.

As @Eddge said, you can't access objects from scenes that aren't loaded.Scene objects are actually created when the scene is loaded, so it's not possible to access them before.

问题在于,当加载新场景时,旧场景(在您的情况下具有要调用SetActive的脚本)已被卸载.

The problem being, when the new scene is loaded, the old scene (with the script that wanted to call SetActive in your case) has been unloaded.

- https://docs.unity3d.com/ScriptReference/Object.DontDestroyOnLoad .html

如果将当前场景中的对象保留在加载的场景中有助于解决您的问题,这是合适的.

This is suitable if having an object from your current scene persist in the loaded scene helps solving your issue.

对于DontDestroyOnLoad无法剪切的情况,可以在不卸载旧场景的情况下加载新场景,从而使您有机会在两者之间传递信息.

For cases when DontDestroyOnLoad doesn't cut it, it's possible to load your new scene without unloading the old one, giving you a chance to pass information between the two.

(这实际上是DontDestroyOnLoad所做的,因为它会将目标对象放到名为DontDestroyOnLoad的场景"中,永远不会卸载)

您可以将SceneManagement.LoadSceneLoadSceneMode.Additive模式一起使用以实现此目的.请注意,在卸载第一个场景之前,这两个场景将同时处于活动状态!

You can use SceneManagement.LoadScene with the mode LoadSceneMode.Additive to achieve that. Be aware that both scenes will be active at the same time until you unload the first one!

请参见 LoadScene LoadSceneAsync UnloadSceneAsync .

您还可以简单地将数据存储在应用程序整个生命周期中都保留的静态字段中,以在整个场景中保留数据和参考.传递一些原始类型可能是一个更简单的解决方案,但请记住它们是 globals ,因此存在相同的缺点.

You can also simply store data in static fields, which are kept throughout your app's lifetime, to retain data and references across scenes.That might be a simpler solution to pass a few primitive types, but remember that they are globals, and thus suffer the same drawbacks.

请参见单人模式

这篇关于是否启用Unity中另一个场景中存在的gameObject?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 19:45