c# - C# Unity 序列化哈希表永远不会被分配
问题描述
我正在做一个游戏。我有一个 ProgressControl 类来跟踪玩家进度,并将其保存并加载到二进制文件中。序列化金币和积分有效。现在我想添加一个哈希表来保存每个关卡的点数,以限制玩家在每个关卡上可以获得的最大点数。但是 Serializable 类中的 Hashtable 永远不会被分配并保持为空。所以没有积分被保存。
我怎样才能得到那个哈希表序列化?我错过了什么?
using UnityEngine;
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Collections;
public class ProgressControl : MonoBehaviour
{
public static ProgressControl progress;
public int gold;
public int points;
public int level;
public Hashtable h;
void Awake()
{
h = new Hashtable();
if (progress == null)
{
DontDestroyOnLoad(gameObject);
progress = this;
}
else if (progress != this)
{
Destroy(gameObject);
}
}
public void save()
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Create(Application.persistentDataPath + "/playerInfo.dat");
PlayerData data = new PlayerData();
data.gold = gold;
data.points = points;
data.h = h;
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();
gold = data.gold;
points = data.points;
h = data.h;
}
}
public void saveLevel()
{
level = TargetScript.activeLevel;
Debug.Log("Level Saved");
}
public void savePointsToHashMap(int LevelKey, int points)
{
if (h.ContainsKey(LevelKey))
{
object value = h[LevelKey];
int compare = int.Parse(value.ToString());
if (compare < points)
{
h.Add(LevelKey, points);
Debug.Log("Overwrite and Save Points");
}
}
else{
Debug.Log("Save Points");
h.Add(LevelKey, points);
}
save();
}
}
[Serializable]
class PlayerData
{
public int gold;
public int points;
public Hashtable h;
}
解决方案
推荐阅读
- java - 使用 Mockito 2 模拟服务导致存根错误
- java - 两个同步的 ScrollPanes 未对齐
- linked-list - Python链表在末尾删除节点
- excel - 如何在excel vba上简化这个?可能吗?
- sql - mysql错误,springframework.jdbc.BadSqlGrammarException:我收到错误消息,找不到原因
- flutter - 如何将我的列表视图宽度设置为全屏宽度以及如何使其自动滚动
- c - 尝试在 CMake 中将 SDL2_mixer 和 SDL2 添加为 ExternalProject
- android - 我的改造响应正文为空,但它适用于 Postman
- graphql - 如何处理 GraphQL 中的嵌套输入
- symfony - Symfony:查询生成器:可捕获的致命错误:DateTime 类的对象无法转换为字符串