Search code examples
c#unity-game-engineserializationwaitbinaryformatter

Detect when Binary Formatter finishes serializing


I have a "Save And Quit" Button in my Game. I Made it and it saves the game as intended. Everything works fine, HOWEVER if i then want to close the game, I need to know when the serialization finished because if i close the game to early its not saved :(. I await some good answers :). Thanks in advance, Here's the code (that works!):

BinaryFormatter formatter = new BinaryFormatter();
string path = Application.persistentDataPath + "/Gmaster.fun";

FileStream stream = new FileStream(path, FileMode.Create);

PlayerData data = new PlayerData();

Formatter.Serialize(stream, data);
stream.Close();

Solution

  • Create an Event and invoke it from the class:

    public event System.Action OnSerializeDone;
    

    somewhere else:

    thatClass.OnSerializeDone += MyClass_SerializeDone;
    

    at the end of your code:

    OnSerializeDone?.Invoke();