Deserializing through BinaryFormatter a file from Assets.

I am currently trying to make Unity load a level from Resources and then deserialize it through BinaryFormatter to get level information.

    public static LevelInformation LoadLevelOfficial (string name) {
        Object levelFile = Resources.Load("/Levels/" + name + ".lvl");
        if (levelFile) {
            BinaryFormatter formatter = new BinaryFormatter ();
            FileStream stream = new FileStream (levelFile, FileMode.Open);
            LevelInformation data = formatter.Deserialize (stream) as LevelInformation;
            stream.Close ();
            return data;
        } else {
            Debug.LogError ("No official level called " + name + "can be found in the game files!");
            return null;
        }
    }

The code crashes at the FileStream line, telling me I can’t deserialize an object directly.
Assets/Resources/Scripts/SaveSys/SaveSystem.cs(100,40): error CS1503: Argument `#1' cannot convert `UnityEngine.Object' expression to type `System.IntPtr'

Any way to work around this?

You can try renaming your .lvl file to .bytes (which Unity recognises as a non standard binary file). Once that’s done you can load it as a TextAsset and then pass the .bytes pointer to the BinaryFormatter.

e.g.

TextAsset textAsset = Resources.Load("/Levels/" + name + ".bytes") as TextAsset;
Stream stream = new MemoryStream(textAsset.bytes);
BinaryFormatter formatter = new BinaryFormatter();              
LevelInformation data = formatter.Deserialize(stream) as LevelInformation;
stream.Close();
return data;
1 Like

Yep, great, works now! However, the first forward slash and the extension were unnecessary there. Resources.Load() needs them omitted. : )

1 Like