Saving and Loading Data Problems (Nested Data/Having a hard time debugging)...

Hey there,

I’m having trouble with saving and loading nested objects. I have a scene object like this:

[Serializable]
public class SS_SceneObject
{
    public string SceneName;
    public int SceneID;
    public List<O_Object> O_ObjectList = new List<O_Object>();
}

The scene holds 'O_Object’s within a list. I’m wondering if I should be serializing the O_Objects here:

public class SS_O_Object
{
    public GameObject O_Object_gameObject;
    public O_Lists.TriggerType triggerType;
    public List<string> O_List;
    public Vector3 storedPosition;
    public Vector3 storedRotation;
    public enum Control    { Controlled, NotControlled }                                         
    public Control control;
    public int O_Interpreter_CurIndex;
    public Vector3 O_memorizedLocalRotation;
}

The code I’m using to either write or to read from a file isn’t working, and it’s very hard to debug right now as there’s no way to just check if the data wrote to the file or not…

I don’t really care that the file is in binary. I’m using the following type of code for opening:

//Create scene object
            SS_SceneObject sceneObject = new SS_SceneObject ();
            //Open file
            BinaryFormatter binaryFormatter = new BinaryFormatter ();
            FileStream fileStream = File.Open (Application.dataPath + "/Maps/Map" + sceneID + ".map", FileMode.Open);
            //Write to scene object
            sceneObject = (SS_SceneObject)binaryFormatter.Deserialize (fileStream);
            //Close file
            fileStream.Close ();

I’m considering using XML or JSON files instead. Isn’t there a way to just write the file straight to a text file without converting it to binary, so that I can debug it more easily?

An update on this, I just ended up using XML files instead, as you can’t serialize a Vector3 among other things using the basic binary formatter.

Your SS_O_Object contains a reference to a GameObject, and you’re trying to serialize it manually.

That’s not going to work. GameObjects, and everything else that inherits from UnityEngine.Object, lives a double life - one version exists in your C# user code, and one exist on the c++ engine side. This means that whenever you’re working with a UnityEngine.Object, Unity must create it, you cannot create it through a constructor or a serialization library.

Your SS_O_Object looks like a class that Unity’s serialization system would handle. There’s no nested structures or anything fancy. So the JsonUtility class would probably handle the job.

1 Like

Thanks Baste. I realized this yesterday when reading up on it. I’m just saving the values I need and forgetting about the reference to the object as it will exist in the scene anyway.

I’ve been considering Json, but xml seems to be working at the moment just fine, as I don’t care about hiding anything (I can just create a hidden folder or something I don’t know).