我在做一个简单的游戏管理器。我有一个脚本,这将从游戏中的所有场景可访问。在加载新场景后,我需要检查它的变量的值。但我的代码在开始模拟后只运行一次,而所有场景中都存在使用此脚本的对象。怎么啦?为什么它在加载新场景后不起作用?
发布于 2018-08-29 13:57:20
这是如何开始你喜欢的任何场景,并确保重新整合你的_preload场景,每次你点击播放按钮在unity编辑器中。从Unity 2017 RuntimeInitializeOnLoadMethod
开始有新的属性可用,关于它的更多信息here。
基本上,您有一个简单的plane c#类和一个带有RuntimeInitializeOnLoadMethod
的静态方法。现在,每次你开始游戏时,这个方法都会为你加载预加载的场景。
using UnityEngine;
using UnityEngine.SceneManagement;
public class LoadingSceneIntegration {
#if UNITY_EDITOR
public static int otherScene = -2;
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
static void InitLoadingScene()
{
Debug.Log("InitLoadingScene()");
int sceneIndex = SceneManager.GetActiveScene().buildIndex;
if (sceneIndex == 0) return;
Debug.Log("Loading _preload scene");
otherScene = sceneIndex;
//make sure your _preload scene is the first in scene build list
SceneManager.LoadScene(0);
}
#endif
}
然后,在_preload场景中有另一个脚本,该脚本将加载回所需的场景(从开始的位置):
...
#if UNITY_EDITOR
private void Awake()
{
if (LoadingSceneIntegration.otherScene > 0)
{
Debug.Log("Returning again to the scene: " + LoadingSceneIntegration.otherScene);
SceneManager.LoadScene(LoadingSceneIntegration.otherScene);
}
}
#endif
...
发布于 2020-05-14 04:38:19
从2019年5月起不使用_preload
的替代解决方案
https://low-scope.com/unity-tips-1-dont-use-your-first-scene-for-global-script-initialization/
我从上面的博客中改写成了下面的操作指南:
为所有场景加载静态资源预置
在Project > Assets
中,创建一个名为Resources
的文件夹。
从一个空的GameObject
创建一个Main
预置并放置在Resources
文件夹中。
在Assets > Scripts
中或任何位置创建一个Main.cs
C#脚本。
using UnityEngine;
public class Main : MonoBehaviour
{
// Runs before a scene gets loaded
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
public static void LoadMain()
{
GameObject main = GameObject.Instantiate(Resources.Load("Main")) as GameObject;
GameObject.DontDestroyOnLoad(main);
}
// You can choose to add any "Service" component to the Main prefab.
// Examples are: Input, Saving, Sound, Config, Asset Bundles, Advertisements
}
将Main.cs
添加到Resources
文件夹中的Main
预置中。
请注意它是如何使用RuntimeInitializeOnLoadMethod
以及Resources.Load("Main")
和DontDestroyOnLoad
的。
将需要跨场景全局的任何其他脚本附加到此预置。
请注意,如果将其他场景游戏对象链接到这些脚本,则可能需要在这些脚本的Start
函数中使用类似以下内容:
if(score == null)
score = FindObjectOfType<Score>();
if(playerDamage == null)
playerDamage = GameObject.Find("Player").GetComponent<HitDamage>();
或者更好的是,使用资产管理系统,如Addressable Assets或Asset Bundles。
https://stackoverflow.com/questions/35890932
复制相似问题