2015-12-07 20 views
2

我在Unity上製作了一個類似Clicker的Android遊戲,每當遊戲中發生一些事情時,我需要存儲一些數據,但它會是非常簡單的數據,就像一些整數和字符串一樣。是否可以使用json之類的方式將其序列化並存儲在文件中?如何以統一的方式在Android中存儲簡單的數據?

+1

可能是你可以使用首選項(http://developer.android.com/reference/android/content/SharedPreferences.html) – droidev

+2

可能重複的[如何在Android應用程序中保存數據](http:///stackoverflow.com/questions/10962344/how-to-save-data-in-an-android-app) –

+0

對於你目前的問題,我建議你將這個遊戲相關的數據存儲在sqlite數據庫文件中(請點擊鏈接由@VividVervet給出)。我不推薦共享前綴,因爲它們可以被清除。 –

回答

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

1

爲什麼要將它存儲在JSON中,您可以簡單地使用PlayerPref。如果您在獲取數據時遇到任何困難,那麼this也會對您有所幫助。

存儲和訪問遊戲會話之間的玩家偏好。

相關問題