Unity-数据保存和加载

Unity-数据保存和加载

Json

使用Unity自带的JsonUtility

1
2
string dataString = JsonUtility.ToJson(data);
data = JsonUtility.FromJson<SaveData>(dataString);

XML

二进制

适用于玩家存档

使用BinaryFormatter序列化和反序列化二进制数据,使用FileStream创建或打开文件流

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

[Serializable]
public class SaveData {
public int HP;
public int atk;
};

public class JsonTest : MonoBehaviour
{
[SerializeField] public SaveData data;

private void OnGUI()
{
string filePath = Application.persistentDataPath + "/game.save";
if(GUILayout.Button("Save"))
{
BinaryFormatter formatter = new BinaryFormatter();
using(FileStream file = File.Create(filePath)) {
formatter.Serialize(file, data);
}
Debug.Log("save at: " + filePath);
}
if(GUILayout.Button("Load"))
{
if(File.Exists(filePath))
{
BinaryFormatter formatter = new BinaryFormatter();
using(FileStream file = File.Open(filePath, FileMode.Open)) {
data = formatter.Deserialize(file) as SaveData;
}
Debug.Log("load at: " + filePath);
}
}
}
}


Unity-数据保存和加载
http://example.com/2022/11/13/Unity-数据保存和加载/
作者
Chen Shuwen
发布于
2022年11月13日
许可协议