android - 如何与Unity一起存储简单的数据?

标签 android json database unity-game-engine

我在Unity上制作类似点击器的Android游戏,每次游戏中发生任何事情时,我都需要存储一些数据,但这将是非常简单的数据,例如某些INT和字符串。它可以使用JSON之类的东西序列化并存储在文件中吗?

最佳答案

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);
        }

持久数据路径的简单示例:

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;

}

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

关于android - 如何与Unity一起存储简单的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34126413/

相关文章:

android - 从 SQLite 数据库中检索特定列

android - 我无法在我的 Android 应用程序中从 mysql 检索数据

jquery - 查询Json并传递变量?

javascript - jQuery - 如何分离依赖于同一对象的两个对象?

sql - 如何从包含单引号的oracle数据库中搜索数据

java - Android 和 Google Play : how to get/getting provider tag data?

android - 获取给定 UUID 的 BluetoothGattCharacteristic

java - Glide : How to stop glide from loading images from cache instead load from server each time

ios - 正确处理Realm对象删除

python - 将值保存到数据库 Django