我在Unity上製作了一個類似Clicker的Android遊戲,每當遊戲中發生一些事情時,我需要存儲一些數據,但它會是非常簡單的數據,就像一些整數和字符串一樣。是否可以使用json之類的方式將其序列化並存儲在文件中?如何以統一的方式在Android中存儲簡單的數據?
2
A
回答
1
正如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);
}
一個簡單的例子爲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也會對您有所幫助。
存儲和訪問遊戲會話之間的玩家偏好。
相關問題
- 1. 最佳方式爲數據存儲在簡單的數據
- 2. 以簡單的方式存儲和刪除數據
- 3. 在Android中以編程方式設置簡單數據格式
- 4. 在Android的在線數據庫中存儲簡單的信息
- 5. 以最簡單的方式在ASP.NET中存儲2個變量
- 6. Android如何保存簡單的數據
- 7. 如何以簡單的方式從數據庫中僅提取一個數據?
- 8. 以數據庫方式存儲一些數據在PHP中
- 9. 如何以簡單的方式從對象中檢索數據?
- 10. 什麼是存儲簡單空間數據的最佳方式
- 11. 如何在android中以編程方式在設備的內部存儲器中存儲數據
- 12. clojure中的簡單數據庫存儲
- 13. Python中的簡單數據存儲
- 14. 在我的系統中存儲數據以供檢索的最佳方式
- 15. 如何在sqlite數據庫中存儲統一地形數據?
- 16. 如何以簡單的方式刪除我的數據庫
- 17. 如何在Access中以簡單的方式過濾不同的數據(參數)?
- 18. 在shopify中存儲數據的方式
- 19. 如何在Android應用程序中存儲簡單的只讀數據庫?
- 20. 如何在Android中存儲簡單的靜態預定義數據
- 21. 最簡單的方式來獲得一個GAE數據存儲的條目
- 22. 在電腦上存儲數據的最簡單的方法
- 23. 如何以最佳方式在Android中存儲和修改分類數據
- 24. 是否可以將表單數據簡單地存儲在模式按鈕中?
- 25. 如何在MySQL存儲_function_中評估一個簡單的數學公式?
- 26. 在mysql數據庫中存儲簡單的數據
- 27. PHP:在數據庫中存儲簡單緩存數組的有效方法?
- 28. 在Phonegap中存儲值的最簡單方法Android
- 29. 尋找一種簡單而簡約的方式在雲中存儲小數據包
- 30. 如何以逗號分隔的方式存儲數據庫值?
可能是你可以使用首選項(http://developer.android.com/reference/android/content/SharedPreferences.html) – droidev
可能重複的[如何在Android應用程序中保存數據](http:///stackoverflow.com/questions/10962344/how-to-save-data-in-an-android-app) –
對於你目前的問題,我建議你將這個遊戲相關的數據存儲在sqlite數據庫文件中(請點擊鏈接由@VividVervet給出)。我不推薦共享前綴,因爲它們可以被清除。 –