首页 > 解决方案 > 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;

}

标签: c#unity3dserializationhashtable

解决方案


推荐阅读