【问题标题】:Getting error while trying to serialize int尝试序列化 int 时出错
【发布时间】:2017-12-07 22:14:16
【问题描述】:

我正在尝试序列化我的整数,但出现以下错误:

InvalidCastException:无法从源类型转换为目标类型。

SaveLoad.Load()(在 Assets/SaveLoad.cs:24)指的是另一个 仅在唤醒时加载它的脚本loadgame.Awake()(在 Assets/loadgame.cs:8) 指的是

StatContainer.totalcoins = (int)bf.Deserialize(file);

我是数据序列化的新手,有人可以解释我的错误在哪里吗?

using UnityEngine;
using System.Collections;
using System.Collections.Generic; 
using System.Runtime.Serialization.Formatters.Binary; 
using System.IO;

public static class SaveLoad {
//public static List<StatContainer> savedGames = new List<StatContainer>();

//it's static so we can call it from anywhere
public static void Save() {
    //SaveLoad.savedGames.Add(StatContainer.current);
    BinaryFormatter bf = new BinaryFormatter();
    //Application.persistentDataPath is a string, so if you wanted you can put that into debug.log if you want to know where save games are located
    FileStream file = File.Create (Application.persistentDataPath + "/savedGames.gd"); //you can call it anything you want
    bf.Serialize(file, StatContainer.current);
    file.Close();
}   

public static void Load() {
    if(File.Exists(Application.persistentDataPath + "/savedGames.gd")) {
        BinaryFormatter bf = new BinaryFormatter();
        FileStream file = File.Open(Application.persistentDataPath + "/savedGames.gd", FileMode.Open);
        StatContainer.totalcoins = (int)bf.Deserialize(file);
        file.Close();
        Debug.Log ("Loaded");
    }
}
}

【问题讨论】:

  • 你能标出错误所指的行吗?
  • @Dragonthoughts 完成!
  • 如果你得到 null 使用 int?而不是 int。
  • 什么是StatsContainer.current?保存文件是使用 this 保存代码创建的,还是之前的尝试遗留下来的(保存了不同的数据?)。

标签: c# unity3d serialization


【解决方案1】:

调用Debug.Log(bf.Deserialize(file)); 看看它返回的是什么类型的对象,因为它显然不是一个int。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-02
    • 2019-01-13
    相关资源
    最近更新 更多