So I’m writing my own serializing method for a quick little app I’m making and have been running into some issues.
I have a data structure called SaveableData which stores a whole bunch of information that is important to resuming the state when the game is loaded. The SaveableData class is what gets serialized to the hard drive by my Binary Formatter.
public class SaveLoad : MonoBehaviour
{
public string saveName = "Tech_Tree_01";
public string savePath = "/";
public void SaveData(SaveableData dataToSave)
{
string path = Application.persistentDataPath + savePath + saveName + ".dat";
FileStream userFile;
if(!File.Exists(path))
{//If the file isn't here, create it
userFile = File.Create(path);
userFile.Close();
}
//Then push all the data we need to save into this file
BinaryFormatter binaryFormatter = new BinaryFormatter();
userFile = File.Open(path, FileMode.Open);
binaryFormatter.Serialize(userFile, dataToSave);//This function serializes all our data to file
userFile.Close();
}
public void LoadData(string path)
{
SaveableData loadedData = new SaveableData();//This is the data that we're gonna load
if(File.Exists(path))
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
FileStream userFile = File.Open(path, FileMode.Open);
loadedData = (SaveableData)binaryFormatter.Deserialize(userFile);
userFile.Close();
}
loadedData.LoadSaveableData();//After we have deserialized everything, load the data
}
SaveableData contains data of the following types: ints, floats, strings, rects, colors, and vector2s. When attempting to serialize this data, I get the following errors:
SerializationException: Type UnityEngine.Rect is not marked as Serializable.
SerializationException: Type UnityEngine.Vector2 is not marked as Serializable.
SerializationException: Type UnityEngine.Color is not marked as Serializable.
According to the documentation, the following is serializable:
- All classes inheriting from UnityEngine.Object, for example
GameObject, Component, MonoBehaviour,
Texture2D, AnimationClip… - All basic
data types like int, string, float,
bool. - Some built-in types like
Vector2, Vector3, Vector4, Quaternion, Matrix4x4, Color,
Rect, LayerMask… - Arrays of a serializable type- List of a serializable type (new in Unity2.6)
- Enums
NOTE: I have properly placed the [System.Serializable] Attribute at the top of the classes. My current version is 4.5 Pro.
I’ve looked all over and I can’t find anyone else having these issues. Where am I going wrong? Is the documentation incorrect or am I making a mistake?
I'm hoping this is not the case, as I would very much like to avoid doing that. It would make large data structures look VERY sloppy
– BadAssGames