max anderson
max anderson

Reputation: 33

How do I serialize ScriptableObjects?

I'm using a save system I don't fully understand but works well. It saves serializable code, but I started using ScriptableObjects as a way to save inventory and it broke and I don't know how to fix it now.

This is the code I'm using:

[CreateAssetMenu(fileName = "Attack")]
 public class PlayerAttckCard : ScriptableObject
{
    public string AtackName,bookName;
    public bool multiTarget;
    public float Bacepower;
    public GameObject miniGame;
}

I tried using [System.Serializable] but I got this error:

SerializationException: Type UnityEngine.ScriptableObject in assembly UnityEngine.CoreModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null is not marked as serializable.

Do I need to change how I'm saving my game or is there a way to fix this?

Upvotes: 3

Views: 12098

Answers (3)

Sid Chou
Sid Chou

Reputation: 17

you should be able to use it, you can put them together or seperate, im getting no error

[CreateAssetMenu(fileName = "item.asset",menuName = "inventory/item")][ System.Serializable]
public class Item:ScriptableObject

or

[CreateAssetMenu(fileName = "item.asset",menuName = "inventory/item"), System.Serializable]
public class Item:ScriptableObject

Upvotes: 0

DangerMouse
DangerMouse

Reputation: 128

Serializing to JSON? You can do this with JsonUtility.

https://docs.unity3d.com/Manual/JSONSerialization.html

public class TestObject : ScriptableObject
{
    public string foo, bar;
}

var obj = ScriptableObject.CreateInstance<TestObject>();
obj.foo = "hello";
obj.bar = "world";
var json = JsonUtility.ToJson(obj);
Debug.Log(json); // {"foo":"hello","bar":"world"}

obj.foo = "something";
obj.bar = "else";
JsonUtility.FromJsonOverwrite(json, obj);
Debug.Log(obj.foo + ", " + obj.bar); // hello, world

Upvotes: 7

Lobsang White
Lobsang White

Reputation: 107

As much as I know, you can't, it's possible doing a custom inspector, editor, gui, but it's quite tricky, I don't know how to do it even. but maybe, you can to do this.

[System.serializable]
public class PlayerAttackCard
{
   public string AtackName,bookName;
   public bool multiTarget;
   public float Bacepower;
   public GameObject miniGame;
}

And the scriptable object.

public class PlayerAttackCardData : ScriptableObject
{
    public PlayerAttackCard playerAttackCard = new PlayerAttackCard();
}

Upvotes: 1

Related Questions