- Home /
Serialization problems with System.IO.MemoryStream
I have been working on saving my game information though serialization, but i encountered a few problems with the C# code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
public class PPSerialization {
public static BinaryFormatter binaryFormater = new BinaryFormatter ();
public static void Save(string saveTag, object obj) {
MemoryStream memoryString = new MemoryStream ();
**binaryFormater.Serialize (MemoryStream, obj);
string temp = System.Convert.ToBase64String(MemoryStream.ToArray());**
PlayerPrefs.SetString (saveTag, temp);
}
public static object Load(string saveTag){
string temp = PlayerPrefs.GetString (saveTag);
if (temp == string.Empty) {
return null;
}
MemoryStream memoryStream = new MemoryStream (System.Convert.FromBase64String(temp));
return binaryFormater.Deserialize (memoryStream);
}
}
The system says there are problems with the lines in bold. The code is old so I don't know if i need to update it or if it's a simple mistake. If anyone could help that would be grateful.
The lines in bold are the ones with two asterisks around them.
Answer by ShadyProductions · Aug 03, 2017 at 09:16 AM
When you use any stream always use the 'using' space, so the stream disposes of its objects correctly.
using(MemoryStream memStream = new MemoryStream(100))
{
//code
}
Also
binaryFormater.Serialize (MemoryStream, obj);
string temp =
System.Convert.ToBase64String(MemoryStream.ToArray());
you are directly passing the MemoryStream type, shouldn't you be passing your stream object
memoryString
Final result:
string temp = string.Empty;
using (MemoryStream memoryString = new MemoryStream ()) {
binaryFormater.Serialize (memoryString, obj);
temp = System.Convert.ToBase64String(MemoryStream.ToArray());
}
Don't forget to add the using in the load function too.
Your answer
Follow this Question
Related Questions
Save/Load Animation State of Instantiated Prefabs 0 Answers
Multiple Cars not working 1 Answer
Serialization Location 1 Answer
Distribute terrain in zones 3 Answers
I am getting a serialization exception error when trying to save and load in Unity? 2 Answers