我在GameController
中有一个Scene1
,我做到了DontDestroyOnLoad
。
当我加载Scene2
时,我试图在GameObject
中找到一个Scene2
,而obj2
是null
,但是{{1} }不是。
为什么?
如何找到obj1
?
GameObjectInScene2
答案 0 :(得分:0)
Start
,因此不再调用
您可以注册到SceneManager.sceneLoaded
并在回调中进行查找。
我还将像全局存储引用一样
private GameObject obj1;
private GameObject obj2;
void Start()
{
// This first line just makes sure the listener isn't added twice
SceneManager.sceneLoaded -= OnSceneLoaded;
// Whenever a scene is loaded call OnSceneLoaded
SceneManager.sceneLoaded += OnSceneLoaded;
obj1 = GameObject.Find("GameObjectInScene1");
SceneManager.LoadScene("Scene2");
}
void OnDestroy ()
{
// Allways clean up listeners when not needed anymore!
SceneManager.sceneLoaded -= OnSceneLoaded;
}
void OnSceneLoaded(Scene scene, LoadSceneMode mode)
{
if(scene.name == "Scene2")
{
obj2 = Find("GameObjectInScene2");
}
}