跳至主要內容
  • Hostloc 空間訪問刷分
  • 售賣場
  • 廣告位
  • 賣站?

4563博客

全新的繁體中文 WordPress 網站
  • 首頁
  • 如何实现存储和加载游戏数据
未分類
14 5 月 2020

如何实现存储和加载游戏数据

如何实现存储和加载游戏数据

資深大佬 : unn 54

本文转自 Unity Connect 博主 Michael Wang

特别针对 ScriptableObject 的特殊性来实现存储和加载

提到存储,目前 Unity 中常用的存储有:XML、Json、PlayerPrefs。

今天我们就用 Binary 二进制和 Json 结合我们之前的背包系统来真是存储我们的游戏数据(背包数据)有关背包系统的内容可以参考另外一篇文章:

https://connect.unity.com/p/kuai-su-zuo-yi-ge-jian-dan-de-bei-bao-xi-tong?app=true

要存储文件就需要得到游戏文件的路径从而创建文件夹和存储的文件

我们使用 Unity 提供的 Application.persistentDataPath 来获得不同平台的游戏目录。

public void SaveGame()

{      Debug.Log(Application.persistentDataPath);//找不到的小伙伴就 Debug 一下程序路径喽~      if (!Directory.Exists(Application.persistentDataPath + "/game_SaveData"))//判断是否有存储文件夹      {          Directory.CreateDirectory(Application.persistentDataPath + "/game_SaveData");//创建文件夹      }  } 

接下来我们就来创建一个用来存储数据的文件了:

public void SaveGame()

{      Debug.Log(Application.persistentDataPath);//程序路径      if (!Directory.Exists(Application.persistentDataPath + "/game_SaveData"))//判断是否有存储文件夹      {          Directory.CreateDirectory(Application.persistentDataPath + "/game_SaveData");//创建文件夹      }      BinaryFormatter formatter = new BinaryFormatter();//二进制转化      FileStream file = File.Create(Application.persistentDataPath + "/game_SaveData/inventory.txt");//创建存储文件,扩展名随便      var json = JsonUtility.ToJson(myInventory);//转换成 Json 格式      formatter.Serialize(file, json);//序列化将 json 变量的 string 内容保存在 file 里面      file.Close();  } 

完成了以上保存的代码,我们做两个 UI – Button 来执行 SaveGame() 和 LoadGame() 并点击 Save 保存一下测试。

我们找到对应平台的文件夹下的文件:

想要打开并读取这里的数据,我们需要一些能读取二进制的软件,这里我用 iHex 打开它:

我们发现右侧能明显看出来我的 itemList 里面的结构,instanceID:0 代表没有数据 这样我们就成功的保存了 ScriptableObject 了。结下的 Load 方法也类似:

public void LoadGame()

{      BinaryFormatter bf = new BinaryFormatter();      if (File.Exists(Application.persistentDataPath + "/game_SaveData/inventory.txt"))      {          FileStream file = File.Open(Application.persistentDataPath + "/game_SaveData/inventory.txt", FileMode.Open);          JsonUtility.FromJsonOverwrite((string)bf.Deserialize(file), myInventory);          file.Close();      }  } 

原文链接: https://connect.unity.com/p/ru-he-shi-xian-cun-chu-he-jia-zai-you-xi-shu-ju?app=true 更多干货,欢迎戳上方链接下载 Unity Connect 官方 app,在线技术答疑,交友学习两不误!

大佬有話說 (0)

文章導覽

上一篇文章
下一篇文章

AD

其他操作

  • 登入
  • 訂閱網站內容的資訊提供
  • 訂閱留言的資訊提供
  • WordPress.org 台灣繁體中文

51la

4563博客

全新的繁體中文 WordPress 網站
返回頂端
本站採用 WordPress 建置 | 佈景主題採用 GretaThemes 所設計的 Memory
4563博客
  • Hostloc 空間訪問刷分
  • 售賣場
  • 廣告位
  • 賣站?
在這裡新增小工具