我已编写此代码,并尝试将数据保存并加载到Unity中。这是我的代码:
using UnityEngine;
using System.Collections;
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Collections.Generic;
using System.Linq;
public class GameControl : MonoBehaviour
{
public static GameControl control;
public float health =10;
public float experience=10;
public Dictionary<string, object> Name_Dic = new Dictionary<string, object>()
{
{"laura",""},
{"steph ",""},
{"Ryan",""},
};
void Start()
{
control = this;
}
void OnGUI()
{
GUI.Label(new Rect(10,10,100,30),"Health"+health);
GUI.Label(new Rect(10,40,100,30),"Experience"+experience);
}
public void Save()
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Create(Application.persistentDataPath +"/playerInfo.dat");
PlayerData data = new PlayerData();
data.experience = experience;
data.health = health;
data.Name_Dic = Name_Dic;
bf.Serialize(file, data);
file.Close();
}
public void Load()
{
if(File.Exists(Application.persistentDataPath+"/playerInfo.dat"))
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath+"/playerInfo.dat",FileMode.Open);
PlayerData data = (PlayerData)bf.Deserialize(file);
file.Close();
health = data.health;
experience = data.experience;
Name_Dic = data.Name_Dic;
}
}
}
[Serializable]
class PlayerData
{
public float health;
public float experience;
public Dictionary<string, object> Name_Dic = new Dictionary<string, object>()
{
{"laura",""},
{"steph ",""},
{"Ryan",""},
};
public Dictionary<string, string> Dialogs_Dic = new Dictionary<string, string>()
{
{"A1", "Hello"},
{"A2", "Nice"},
{"A3", "Test"},
};
}
现在的问题是,当我点击保存按钮时,我保存了健康和体验int,因为当我点击加载按钮时我确认这两个变量被保存并加载。我的问题是字典,我不知道当我点击按钮保存字典值是否保存。如果单击保存并加载的功能,如果我点击按钮加载,如果保存字典值,我现在怎么办呢。有一个解决方案,谢谢你的帮助