I’m trying to serialize a GameObject (with children and textures) using the binary serialization for C#.
It works with many data types but not with GameObject. In the docs it says should be serializable (Unity - Scripting API: SerializeField):
"
Serializable types are:
- All classes inheriting from UnityEngine.Object, for example GameObject …
"
I’ve read suggestions of using the asset of UnitySerialization, but that is overkill for me, I just need to store a GameObject on my scene (that will be generated by many users) and load them all in another scene.
This is the code (I’m following this tutorial:
):
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
public class GameControl : MonoBehaviour {
public static GameControl control;
public GameObject drawing;
public string drawName;
//I could delete the AWAKE.
void Awake () {
if (control == null)
{
DontDestroyOnLoad(gameObject);
control = this;
}
else if (control != this)
{
Destroy(gameObject);
}
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public void Save ()
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Create(Application.persistentDataPath + "/drawing.drawli");
UserDraw data = new UserDraw();
data.drawing = drawing;
bf.Serialize(file, data);
file.Close();
}
public void Load()
{
if (File.Exists(Application.persistentDataPath + "/drawing.draw"))
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/drawing.draw", FileMode.Open);
UserDraw data = (UserDraw)bf.Deserialize(file);
file.Close();
drawing = data.drawing;
}
}
}
[System.Serializable]
class UserDraw
{
public GameObject drawing;
}
Check the Save/Load functions. I’m just trying to store the “drawing” (GamObject), save it and load it. That’s all! Is very simple. With other data types it works. But not with GameObject.
This is the (execution) error:
SerializationException: Type UnityEngine.GameObject is not marked as Serializable.