欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SerializationException Unity中BinaryFormatter反序列化错误

程序员文章站 2022-04-03 12:29:09
...
SerializationException: The ObjectManager found an invalid number of fixups. This usually indicates a problem in the Formatter.

下面是错误示范:
保存二进制:

			AssetBundleConfig config = new AssetBundleConfig();
        //string bytePath = "Assets/GameData/Data/ABData/AssetBundleConfig.bytes";
        //FileStream fs = new FileStream(bytePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
        //BinaryFormatter bf = new BinaryFormatter();
        //bf.Serialize(fs, config);
        //fs.Close();

读取二进制:

  BinaryFormatter bf = new BinaryFormatter();
        MemoryStream stream = new MemoryStream(textAsset.bytes);
        AssetBundleConfig config = (AssetBundleConfig)bf.Deserialize(stream);
        stream.Close();

最后改进方案:

//保存为二进制
private static void SaveBin(AssetBundleConfig config)
    {
        try
        {
            string path = "Assets/GameData/Data/ABData/AssetBundleConfig";
            FileStream file = null;
            BinaryFormatter bf = new BinaryFormatter();
            file = File.Open(path, FileMode.Create);
            bf.Serialize(file, config);
            file.Close();
        }
        catch (System.Exception ex)
        {
            Debug.LogError("存储失败----" + ex.Message);
        }
        //string.IsNullOrEmpty(path):基本等价与path==null||path.length==0::没用到,但想到。

    }
    // 读取二进制
        public AssetBundleConfig OpenBin()
    {
        string path = "Assets/GameData/Data/ABData/AssetBundleConfig";
        AssetBundleConfig config = null;
        FileStream file = null;
        BinaryFormatter bf = new BinaryFormatter();
        file = File.Open(path, FileMode.Open);
        config = (AssetBundleConfig)bf.Deserialize(file);
        file.Close();
        return config;
    }
    
相关标签: c# unity