unity3D 保存游戏数据和载入游戏数据

原视频地址:Unity教程:如何存储和加载游戏(ScriptableObject)_哔哩哔哩_bilibili

将代码挂在到任意空物体上,例如叫SaveGameManager

需要两个按钮,分别添加点击事件,方法在下方代码中

以下方法是保存背包里的数据,可以参考做出,保存人物个人信息数据,如金币数等

1:保存游戏

2:载入游戏

 1 using System.Collections;
 2 using System.Collections.Generic;
 3 using UnityEngine;
 4 using System.IO;//系统操作库
 5 using System.Runtime.Serialization.Formatters.Binary;//调用二进制库
 6 
 7 public class SaveDataManager : MonoBehaviour {
 8     [Header("我的背包")]
 9     public Bag mybag;
10 
11     /// <summary>
12     /// 保存游戏
13     /// </summary>
14     public void SaveGame() {
15         
16         print("点击了保存游戏按钮");
17 
18         //输出保存位置
19         Debug.Log(Application.persistentDataPath);
20 
21         //判断如果不存在保存文件数据
22         if (!Directory.Exists(Application.persistentDataPath + "/game_SaveData")) {
23 
24             //创建游戏存储目录文件
25             Directory.CreateDirectory(Application.persistentDataPath + "game_SaveData");
26         }
27 
28         //实例化二进制转化工具
29         BinaryFormatter f = new BinaryFormatter();
30 
31         //创建保存文件位置
32         FileStream file = File.Create(Application.persistentDataPath + "game_SaveData/bag.txt");
33 
34         //将背包转换成json格式
35         var json = JsonUtility.ToJson(mybag);
36 
37         //序列化文件,转成二进制
38         f.Serialize(file, json);
39 
40         file.Close();//关闭文件句柄
41 
42         print("数据以保存到:" + Application.persistentDataPath);
43     }
44 
45     /// <summary>
46     /// 加载游戏
47     /// </summary>
48     public void LoadGame() {
49         
50         print("点击了保存游戏按按钮");
51 
52         //实例化二进制转化类
53         BinaryFormatter bf = new BinaryFormatter();
54 
55         //如果游戏保存目录存在
56         if (File.Exists(Application.persistentDataPath + "game_SaveData/bag.txt")) {
57 
58             //打开文件(路径,模式)
59             FileStream file = File.Open(Application.persistentDataPath + "game_SaveData/bag.txt",FileMode.Open);
60 
61             //反序列化json(数据,位置)
62             JsonUtility.FromJsonOverwrite((string)bf.Deserialize(file), mybag);
63 
64             //关闭文件句柄
65             file.Close();
66         }
67         print("完成了保存数据操作");
68     }
69 }
时间若流水,恍惚间逝去
原文地址:https://www.cnblogs.com/alanshreck/p/14864433.html