Serialize GameObject in Unity

2.4k Views Asked by At

I have class like -

[serializable]
public class DemoClass{
    [SerializeField]
    public GameObject gameObject;
}

I want to store data using serializable. Unity doc says GameObject is serializeField. But it gives Exception -

SerializationException: Type UnityEngine.GameObject is not marked as Serializable.

Anyone have idea about it ?

2

There are 2 best solutions below

5
On BEST ANSWER

Add the tag [Serializable] before your class name:

[Serializable]
public class DemoClass{
    public GameObject gameObject;
    public AudioClip audio;
}

Documentation

Edit: ff you still want to serialize GameObject their is some plugins out there that allow to Serialize Unity Objects. See: Runtime Serialization for Unity

1
On

You will need to add the [serializable] attribute to the classes that you wish to serialize. If any of the classes within your class are not already serializable, you will need to add this attribute to those classes as well.

e.g.

[Serializable]
public class DemoClass
{
   public GameObject gameObject;
   public AudioClip audio;
}