如何在Android中统一存储简单数据?

时间:2015-12-07 04:23:57

标签: android json database unity3d

我在Unity上制作类似Clicker的Android游戏,我需要在游戏中发生某些事情时存储一些数据,但这将是非常简单的数据,如一些整数和字符串。用json和文件存储来序列化它是否可行?

2 个答案:

答案 0 :(得分:1)

为什么要将其存储在JSON中,只需使用PlayerPref即可。如果您从中获取数据时遇到任何困难,this也会对您有所帮助。

  

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

答案 1 :(得分: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;的{​​{1}}名称空间。