当场景发生变化时如何运行一些代码?

Mat*_*ack 2 c# unity-game-engine

不知道我能解释得如何。我有一个加载时不破坏的脚本,因此它可以在两个场景之间移动。然而,在一个场景(最初创建的场景)中,我需要它在每次重新进入该场景时运行启动函数,因为它会绘制出我的一些 UI。这是供参考的代码:

我可以尝试将其放入新脚本中,但我担心由于我每周只在这个项目上工作几个小时,因此会有一些代码我忘记适应此更改,并且它将不再工作。如何重新调用启动函数,或者做类似的事情?

int spriteIndex = 0;
    foreach (Sprite texture in spriteImages) {

        GameObject button = Instantiate (shopButtonPrefab) as GameObject;
        Image buttonImage = button.GetComponent<Image> ();
        Image[] images = button.GetComponentsInChildren<Image>();

        int newIndex = spriteIndex;
        button.GetComponent<Button> ().onClick.AddListener (() => ChangePlayerSkin (newIndex));
        spriteIndex++;
        foreach (Image image in images) {

            if (image != buttonImage) {
                //button.GetComponentInChildren<Image>().sprite = texture;
                //button.transform.SetParent (shopButtonContrainer.transform, false);
                image.sprite = texture;


                break;
            }
            button.transform.SetParent (shopButtonContrainer.transform, false);
        }

    }
Run Code Online (Sandbox Code Playgroud)

der*_*ugo 6

您可以为SceneManager.sceneLoadedStart添加侦听器,而不是在其中执行此操作

仅当加载初始场景时才执行这些操作,您可以使用它SceneManager.GetActiveScene()来存储初始场景并稍后将其与加载的场景进行比较。

// Store the scene that should trigger start
private Scene scene;

private void Awake()
{
    // It is save to remove listeners even if they
    // didn't exist so far.
    // This makes sure it is added only once
    SceneManager.sceneLoaded -= OnsceneLoaded;

    // Add the listener to be called when a scene is loaded
    SceneManager.sceneLoaded += OnSceneLoaded;

    DontDestroyOnLoad(gameObject);

    // Store the creating scene as the scene to trigger start
    scene = SceneManager.GetActiveScene();
}

private void OnDestroy()
{
    // Always clean up your listeners when not needed anymore
    SceneManager.sceneLoaded -= OnSceneLoaded;
}

// Listener for sceneLoaded
private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
{
    // return if not the start calling scene
    if(!string.Equals(scene.path, this.scene.path) return;

    Debug.Log("Re-Initializing", this);
    // do your "Start" stuff here
}
Run Code Online (Sandbox Code Playgroud)

Afaik / 我如何理解链接中的示例OnSceneLoaded也将在第一个场景中调用,只要您在之前添加回调Start(因此在Awake或 中OnEnable)。


请注意,我使用Scene.path代替scene.name,因为始终path是唯一的(由于操作系统文件系统),而可能不是。name