gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 20:25:56 24 4
gpt4 key购买 nike

我正在 Unity 上制作一个类似唱首歌的 Android 游戏,我需要在游戏中每次发生某些事情时存储一些数据,但它会是非常简单的数据,比如一些整数和字符串。用 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);
}

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;

}

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








关于android - 如何统一在Android中存储简单数据?,我们在Stack Overflow上找到一个类似的问题:

https://stackoverflow.com/questions/34126413/




24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com