Search code examples
c#unity-game-enginecastingbinaryfilestream

cast object to class C#


Trying to cast .dat file to its own Class

  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

    }

Problem: LoadObjInBinary returning null. The file path is correct and class also matches, but don't know why "(Level0) object" not working...

Thanks


Solution

  • Thank you for providing the Level0 class.

    The problem is that static fields are never serialized, since they do not belong to the instance of the object you intantiate, they are global.

    As I assume you will need them to be static, so they are accessible from all parts of your application, the quick work-around is to create another class with non-static members, then serialize-deserialize it, and assign it's values to the global static instance of Level0 (wherever you use it).

    [Serializable]
    class Level0Data
    {
        int level = 1;
        int moves = 15;
        int seconds;
        int minScoreForOneStar = 1000;
        ...
    }
    

    Then after serialization and deserialization you can do the following.

     Level0Data deserializedObject = (Level0Data) LoadObjInBinary(..);
     Level0.level = deserializedObject.level;
     Level0.moves = deserializedObject.moves;
    

    As you have to make sure that Level0.level, moves and all other members are public, or atleast publicly available for modification in another way.

    Additionaly you have to make sure that

    class TargetObj{}
    class Cell{}
    

    Are also marked as Serializable, otherwise they will not get written on the file, nor any deserialization information regarding them.

    EDIT

    Here you can find all supported in Unity by default serializable types:

    Unity SerializeField