【问题标题】:How to store simple data in Android with unity?如何在Android中统一存储简单数据?
【发布时间】:2015-12-07 04:23:57
【问题描述】:

我正在 Unity 上制作一个类似于 clicker 的 Android 游戏,每次游戏中发生某些事情时我都需要存储一些数据,但这将是非常简单的数据,比如一些整数和字符串。用json之类的东西序列化它并存储在一个文件中是否可行?

【问题讨论】:

  • 也许你可以使用 Preferences (developer.android.com/reference/android/content/…)
  • 对于您当前的问题,我建议您将此游戏相关数据存储在 sqlite 数据库文件中(按照@VividVervet 给出的链接)。我不推荐共享首选项,因为它们可以被清除。
  • @Vishal sh 我觉得“因为它们可以被清除”
  • “清除数据”选项也将删除 sqlite 数据。但我认为,如果用户单击该选项,则该用户很清楚这一事实。对于您的情况,您现在可以使用 SharedPreferences 。但如果您想获取复杂/复合数据,我建议您使用 SQLite。

标签: android json database unity3d


【解决方案1】:

正如Mohammed Faizan Khan所说,您可以使用PlayerPrefspersistentDataPath来保存和访问数据。

PlayerPrefs 的简单示例:

private int score = 0;
private int savedScore;

void Update () {
    if (Input.GetKeyDown (KeyCode.S)) {
        PlayerPrefs.SetInt("Score", score);
        Debug.Log(score);
        }
    if (Input.GetKeyDown (KeyCode.L)) {
        savedScore = PlayerPrefs.GetInt("Score");
        Debug.Log(savedScore);
        }

persistentDataPath 的简单示例:

private string savedName;
private int savedHealth;
private string loadedName;
private int loadedHealth;

public void Save(){
    BinaryFormatter bf = new BinaryFormatter();
    FileStream file = File.Open(Application.persistentDataPath + "/FileName.dat", FileMode.Create);
    PlayerClass newData = new PlayerClass();
    newData.health = savedHealth;
    newData.name = savedName;
    bf.Serialize(file, newData);
    file.Close();
}

public void Load(){

    if (File.Exists(Application.persistentDataPath + "/FileName.dat")){
        BinaryFormatter bf = new BinaryFormatter();
        FileStream file = File.Open(Application.persistentDataPath + "/FileName.dat", FileMode.Open);
        ObjData newData = (ObjData)bf.Deserialize(file);
        file.Close();
        loadedHealth = newData.health;
        loadedName = newData.name;
    }
}

[Serializable]
class PlayerClass{
    public string name;
    public int health;

}

记住,你需要 using System; using System.Runtime.Serialization.Formatters.Binary; using System.IO;persistentDataPath 的命名空间。

【讨论】:

    【解决方案2】:

    为什么要将它存储在 JSON 中,您可以简单地使用 PlayerPref。如果您在从中获取数据时遇到任何困难,this 也会为您提供帮助。

    在游戏会话之间存储和访问玩家偏好。

    【讨论】:

      猜你喜欢
      • 2015-02-05
      • 2018-05-06
      • 1970-01-01
      • 2010-10-26
      • 1970-01-01
      • 2012-04-25
      • 2016-08-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多