Unity中如何保存与加载int类型的List或数组?
修改方案
要实现List<int>的保存与加载,只需对现有代码做以下几处修改:
1. 更新可序列化的SaveData类
在SaveData中添加List<int>类型的字段(List<int>本身支持序列化,无需额外处理),同时保留原有的story字段:
[Serializable] class SaveData { public int story; public List<int> integers; // 新增要保存的int列表字段 }
2. 修改SaveGame方法
保存时将需要存储的integers列表赋值给SaveData对象的对应字段:
public void SaveGame() { BinaryFormatter bf = new BinaryFormatter(); FileStream file = File.Create(Application.persistentDataPath + "/data.file"); SaveData data = new SaveData(); data.story = story; data.integers = integers; // 保存int列表 bf.Serialize(file, data); file.Close(); Debug.Log("Game data saved!"); }
3. 修改LoadGame方法
加载时将序列化文件中的列表赋值回你的integers列表:
public void LoadGame() { if (File.Exists(Application.persistentDataPath + "/data.file")) { BinaryFormatter bf = new BinaryFormatter(); FileStream file = File.Open(Application.persistentDataPath + "/data.file", FileMode.Open); SaveData data = (SaveData)bf.Deserialize(file); file.Close(); story = data.story; integers = data.integers; // 加载int列表 Debug.Log("Game data loaded!"); } else Debug.LogError("There is no save data!"); }
完整修改后的代码
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; using System.Runtime.Serialization.Formatters.Binary; using System.IO; public class Data : MonoBehaviour { public INVENTORY inv; public static int story; public List<int> integers = new List<int>(); // 你的int列表 public void LoadGame() { if (File.Exists(Application.persistentDataPath + "/data.file")) { BinaryFormatter bf = new BinaryFormatter(); FileStream file = File.Open(Application.persistentDataPath + "/data.file", FileMode.Open); SaveData data = (SaveData)bf.Deserialize(file); file.Close(); story = data.story; integers = data.integers; Debug.Log("Game data loaded!"); } else Debug.LogError("There is no save data!"); } public void SaveGame() { BinaryFormatter bf = new BinaryFormatter(); FileStream file = File.Create(Application.persistentDataPath + "/data.file"); SaveData data = new SaveData(); data.story = story; data.integers = integers; bf.Serialize(file, data); file.Close(); Debug.Log("Game data saved!"); } } [Serializable] class SaveData { public int story; public List<int> integers; }
可选:用数组替代List
如果想用数组实现,只需调整两处:
- 将
SaveData中的List<int>改为int[] - 保存时:
data.integers = integers.ToArray(); - 加载时:
integers = new List<int>(data.integers);
内容的提问来源于stack exchange,提问作者JMAS
相关产品推荐
相关产品推荐

