【问题标题】:Find the 'Number' of the Scene the Player is in to Save it in PlayerPref Unity找到玩家所在场景的“编号”以将其保存在 PlayerPref Unity 中
【发布时间】:2020-02-23 03:17:35
【问题描述】:

我正在开发一款 2D Pixel Platformer RPG,我需要在其中开发一个保存和加载机制。游戏中有几个场景(还会有更多),问题是,我如何保存玩家当前所在的场景编号,以便当他退出并重新加载游戏时,他在同一个场景中。如何在 C# Unity 中实现它。 (请清楚,因为我有点初学者)。

【问题讨论】:

标签: c# unity3d


【解决方案1】:

好的,所以您需要做一些事情才能实现这一目标:

首先,在构建的第一个场景中 - 创建一个 Empty GameObject,将其命名为“SceneManager”。

然后,创建一个新标签“SceneManager”并将其添加到“SceneManager”游戏对象中

最后,将“SceneManager”脚本添加到“SceneManager”游戏对象中:

using System.Collections; 
using UnityEngine; 
using UnityEngine.SceneManagement;
public class SceneManager : MonoBehaviour 
{

    void Awake()
    {
        DontDestroyOnLoad(gameObject);
    }
    public void SaveScene()
    {
        int activeScene = SceneManager.GetActiveScene().buildIndex;
        PlayerPrefs.SetInt("ActiveScene", activeScene);
    }
    public void LoadScene()
    {
        int activeScene = PlayerPrefs.GetInt("ActiveScene");
        SceneManager.LoadScene(activeScene);
    }
}

然后,您可以使用此脚本加载/保存场景:

using UnityEngine;
public class UsageScript: MonoBehaviour { 
    private SceneManager SceneManager;
    void Awake ()
    {
        sceneManager = GameObject.FindGameObjectWithTag("SceneManager").GetComponent<SceneManager>();
    }

    void UsageManager()
    {
        sceneManager.SaveScene();

        sceneManager.LoadScene();
    }
}

【讨论】:

  • 不要使用 PlayerPrefs 来存储游戏状态。
  • @Draco18s 为什么不呢?
  • 1) FileStream 可用 2) PlayerPrefs 不支持复杂数据类型 3) 它以纯文本形式存储 4) 它适用于首选项,例如音量级别.
  • 1) 对,但为什么在这种情况下更好?请注意,问题是关于 PlayerPerfs 2)我正在向 PlayerPerfs 发送一个 int 3)我理解 4)从我在这里读到的内容:docs.unity3d.com/ScriptReference/PlayerPrefs.html 看起来 PlayerPerfs 的目的是为了保存玩家所在的场景。@ Draco18s
  • 最好一般不要使用 PlayerPrefs。您可能只保存一个整数here,但有人会尝试保存整个游戏对象。 it looks like PlayerPerfs purpose was for things like saving the scene the player was in 我不知道你是怎么想到的,它说的是“在游戏会话之间存储和访问玩家偏好”,并附有关于在哪里可以找到文件的注释每个操作系统及其方法列表。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-30
  • 1970-01-01
  • 2021-09-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多