Loh Choon Hian
Loh Choon Hian

Reputation: 3

Trying to attach a save script in unity, serialization not working

Hi trying to attach a simple save script into a GameObject (cube) in unity. everything looks fine ( no errors) except for the Serialize part(says 'no overload for method 'Serialize' takes 1 arguments) . can anyone guide me on this?. here is the example of the code. thanks a lot!

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

public class SavingTheGame : MonoBehaviour {

    public void OnTriggerEnter (Collider collider)
    {
            BinaryFormatter bf = new BinaryFormatter();
            FileStream file = File.Create(Application.persistentDataPath + "/SaveGame.dat");


           bf.Serialize(file);
            file.Close();     
    }
}

Upvotes: 0

Views: 144

Answers (1)

Riaan Walters
Riaan Walters

Reputation: 2676

You are not serializing anything, you need to supply the object you would like to serialize

public void OnTriggerEnter (Collider collider)
{
        BinaryFormatter bf = new BinaryFormatter();
        FileStream file = File.Create(Application.persistentDataPath + "/SaveGame.dat");

       // Change here
       var obj = "This Will Be Serialized";
       bf.Serialize(file, obj); 

       file.Close();     
}

BinaryFormatter.Serialize requires 2 parameters, stream and object

You can follow a nice tutorial on using BinaryFormatter in Unity for saving/loading here: https://gamedevelopment.tutsplus.com/tutorials/how-to-save-and-load-your-players-progress-in-unity--cms-20934

Upvotes: 1

Related Questions