【问题标题】:How to load the game, where many scenes in Unity怎么加载游戏,Unity里面很多场景
【发布时间】:2016-12-16 07:51:36
【问题描述】:

在 Unity3d 上的游戏中,我有很多场景,现在我正在处理保存/加载游戏。我可以保存游戏,但如果我想加载它,我需要加载我需要的场景,然后加载所有其他参数。

或者我应该先加载所有参数,用DontDestroyOnLoad()保存,然后加载我需要的场景?

public void ButtonSave()
{
    PlayerPrefs.SetFloat("transform position x" + currentActiveSlot, playerTransform.position.x);
    PlayerPrefs.SetInt("task 1 completed" + currentActiveSlot, isTask1Completed);
    PlayerPrefs.SetInt("latestSaveSlot", latestSaveSlot);
    PlayerPrefs.SetInt("act number" + currentActiveSlot, 0);
    PlayerPrefs.SetInt("step number" + currentActiveSlot, 0);
    PlayerPrefs.SetString("sceneName" + currentActiveSlot, SceneManager.GetActiveScene().name);        
    PlayerPrefs.Save();        
}

public void ButtonLoad()
{
    playerTransform.position = new Vector3(PlayerPrefs.GetFloat("transform position x" + currentActiveSlot),
                                           PlayerPrefs.GetFloat("transform position y" + currentActiveSlot),
                                           PlayerPrefs.GetFloat("transform position z" + currentActiveSlot));

    isTask1Completed = PlayerPrefs.GetInt("task 1 completed" + currentActiveSlot);

    //gameManager.currentActNumber = PlayerPrefs.GetInt("act number" + currentActiveSlot);
    //act_2.stepNumber = PlayerPrefs.GetInt("step number" + currentActiveSlot);
    //SceneManager.LoadScene(PlayerPrefs.GetString("sceneName" + currentActiveSlot));
}

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    您应该首先使用SceneManager.LoadScene 加载场景,然后使用您的PlayerPrefs 代码加载播放器设置。

    public void ButtonLoad()
    {
        SceneManager.LoadScene(PlayerPrefs.GetString("sceneName" + currentActiveSlot));
        playerTransform.position = new Vector3(PlayerPrefs.GetFloat("transform position x" + currentActiveSlot),
                                               PlayerPrefs.GetFloat("transform position y" + currentActiveSlot),
                                               PlayerPrefs.GetFloat("transform position z" + currentActiveSlot));
    
        isTask1Completed = PlayerPrefs.GetInt("task 1 completed" + currentActiveSlot);
    }
    

    单独保存变量不是一个好主意。您可以看到保存和加载场景的正确方法here

    编辑:

    但在我的情况下,加载场景后,方法的其他部分 执行?

    是/否。

    在调用SceneManager.LoadScene 之后,该函数中的其余代码将执行,但执行将在新加载的场景中而不是的相同场景中完成。 因此,您将丢失刚刚加载的播放器设置。

    所以,我认为这对你没有用。将播放器设置代码放在AwakeStart函数中,加载场景后自动加载播放器设置。

    public void ButtonLoad()
    {
        SceneManager.LoadScene(PlayerPrefs.GetString("sceneName" + currentActiveSlot));
    }
    
    void Awake()
    {
        isTask1Completed = PlayerPrefs.GetInt("task 1 completed" + currentActiveSlot);
        //...other PlayerPrefs.GetInt code
    }
    

    【讨论】:

    • 但在我的情况下,加载场景后,该方法的其他部分会执行吗?
    • 加载场景后,您应该将加载代码放在AwakeStart 函数中。所以将PlayerPrefs.GetInt 移动到AwakeStart 函数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多