我在Unity上制作类似点击器的Android游戏,每次游戏中发生任何事情时,我都需要存储一些数据,但这将是非常简单的数据,例如某些INT和字符串。它可以使用JSON之类的东西序列化并存储在文件中吗?
最佳答案
如Mohammed Faizan Khan也就是说,您可以使用 PlayerPrefs
或 persistentDataPath
来保存和访问数据。
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/