将对象强制转换为类C#
试图将.dat文件强制转换为它自己的类将对象强制转换为类C#,c#,unity3d,casting,binary,filestream,C#,Unity3d,Casting,Binary,Filestream,试图将.dat文件强制转换为它自己的类 level0 = (Level0) LoadObjInBinary(level0, "Level" + levelNumber); public static object LoadObjInBinary(object myClass, string fileName) { fileName += ".dat"; if (File.Exists(FileLocation + fileName)) {
level0 = (Level0) LoadObjInBinary(level0, "Level" + levelNumber);
public static object LoadObjInBinary(object myClass, string fileName) {
fileName += ".dat";
if (File.Exists(FileLocation + fileName)) {
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(FileLocation + fileName, FileMode.Open);
myClass = bf.Deserialize(file);
file.Close();
return myClass;
} else {
return null;
}
}
Level() class
[Serializable]
public class Level0 { //Using this class to create Level.dat binary file
static int level = 1;
static int moves = 15;
static int seconds;
static int minScoreForOneStar = 1000;
static int minScoreForTwoStars = 1500;
static int minScoreForThreeStars = 2000;
static TargetObj[] targetObjs = {new TargetObj(Targets.Black, 10), new TargetObj(Targets.Freezer, 1), new TargetObj(Targets.Anchor, 2)};
static Color[] colors = {Constants.grey, Constants.green, Constants.pink, Constants.brown, Constants.purple, Constants.lightBlue};
static Cell[,] levelDesign;
//the rest is Properties of Fields
}
问题:LoadObjInBinary返回null。文件路径正确,类也匹配,但不知道为什么“(Level0)对象”不工作
谢谢谢谢您提供0级课程 问题是静态字段永远不会序列化,因为它们不属于您输入的对象的实例,它们是全局的 由于我假设您需要它们是静态的,因此可以从应用程序的所有部分访问它们,快速解决方法是创建另一个具有非静态成员的类,然后序列化反序列化它,并将其值分配给Level0的全局静态实例(无论您在何处使用它) 然后在序列化和反序列化之后,您可以执行以下操作
Level0Data deserializedObject = (Level0Data) LoadObjInBinary(..);
Level0.level = deserializedObject.level;
Level0.moves = deserializedObject.moves;
因为您必须确保Level0.level、moves和所有其他成员都是公共的,或者至少可以通过其他方式公开修改
另外,你必须确保
class TargetObj{}
class Cell{}
还将标记为可序列化,否则它们将不会写入文件,也不会写入任何有关它们的反序列化信息
编辑
在这里,您可以找到Unity中默认支持的所有可序列化类型:
您还使用BinaryFormatter来序列化
Level0
类型?只是为了科学:你能替换返回空值吗使用返回新的Level0()代码>。我想验证路径是否正确。没有任何更改,该文件存在,并且它确实返回了对象,但无法将其强制转换为Level0()。是的,我使用BinaryFormatter序列化了。您可以为Level0类提供其他信息吗。它是否标记为可序列化?它是否包含其他自定义类型的成员?是的,我编辑了我的问题,请经常检查Thanx,它起作用了,而且我添加了不可序列化的颜色[],我将其更改为具有颜色十六进制值的字符串[]!关于颜色,是的,我认为只有最新版本的Unity支持它的原语序列化。
class TargetObj{}
class Cell{}