【问题标题】:Get active scene when next scene loads加载下一个场景时获取活动场景
【发布时间】:2021-11-27 12:56:00
【问题描述】:

所以我一直在尝试制作游戏,但是当我按下按钮时,场景会自行重新加载。我想要做的是让它在加载场景时获取活动场景的构建索引。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement; 

public class LevelSwitch : MonoBehaviour
{
    int CurrentSceneBuildIndex;

    bool sceneLoaded; 
    void Update()
    {
      if (sceneLoaded == true )
        {
            CurrentSceneBuildIndex = SceneManager.GetActiveScene().buildIndex;
        }
    }
    public void NextLevel()
    {
        SceneManager.LoadScene(CurrentSceneBuildIndex + 3 );
        sceneLoaded = true; 
    }
    public void LevelSelect()
    {
        SceneManager.LoadScene("LevelSelect"); 
    }
    
}

【问题讨论】:

  • 看看如何写一个好问题:stackoverflow.com/tour。您想问的问题适用于 StackOverflow,但需要重写才能对其他人有用并避免投票。你能写一个更具体的问题吗? “所以我一直在尝试制作游戏”什么也没说,“当我按下按钮时”——什么按钮?我想你真正想问的是“如何获取活动场景的构建索引?”其次是“这是我尝试过的......这就是发生的事情......”

标签: unity3d 2d


【解决方案1】:

问题:

好的,所以您的解决方案的问题是,当在 Unity 中加载新场景时,游戏对象及其附加脚本不会保留在场景之间。在您的脚本函数NextLevel() 中,您正在加载场景,然后将sceneLoaded 布尔值设置为true,但是这是在加载新场景之后,我们知道游戏对象及其附加脚本不会在场景之间传输,这意味着这个布尔值也不会转移到下一个场景。除非游戏对象标有dontdestroyonload

那么我们能做些什么来解决这个问题呢?

要在加载场景时获取场景的当前构建索引,您可以将脚本附加到场景中的 GameObject 中,以获取其索引,使用SceneManager.sceneLoaded 检测场景何时完成加载,然后获取索引。 例如:

using UnityEngine;
using UnityEngine.SceneManagement;

public class ExampleCode : MonoBehaviour
{    

    void OnEnable()
    {
        Debug.Log("OnEnable called");
        SceneManager.sceneLoaded += OnSceneLoaded; // This tells the script to call the function "OnSceneLoaded" when the scene manager detects the scene has finished loading with the parameters of the scene object and the mode of how the scene was loaded
    }


    void OnSceneLoaded(Scene scene, LoadSceneMode mode)
    {
        Debug.Log("OnSceneLoaded: " + scene.name + ", Build Index : " + scene.buildIndex.ToString());
        Debug.Log("Load Mode : " + mode);
    }

    // called third
    void Start()
    {
        Debug.Log("Start");
    }

    // called when the game or scene closes
    void OnDisable()
    {
        Debug.Log("OnDisable");
        SceneManager.sceneLoaded -= OnSceneLoaded; // This tells the script to stop calling OnSceneLoaded when the scene manager detects a new scene has been loaded
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-15
    • 1970-01-01
    • 1970-01-01
    • 2020-11-11
    • 1970-01-01
    • 2015-09-07
    相关资源
    最近更新 更多