在DontDestroyOnLoad中的新场景中找不到GameObject

时间:2019-01-02 09:44:27

标签: unity3d

我在GameController中有一个Scene1,我做到了DontDestroyOnLoad

当我加载Scene2时,我试图在GameObject中找到一个Scene2,而obj2null,但是{{1} }不是。

为什么?

如何找到obj1

GameObjectInScene2

1 个答案:

答案 0 :(得分:0)

由于您的组件已经在Scene1中运行了

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");
    }
}