- Home /
How to deserialize class and load script/class onto GameObject?
Hello all,
I have a class that is essentially Inventory for a player and looks something like this:
[System.Serializable]
public class Inventory : MonoBehaviour {
public int Money;
public string equippedItem;
public List<string> items;
}
There's some other code in there that's not important (like PlayerPrefs and saving data). I have successfully been able to use Json to save this data to a Google Play SaveGame file, but have been unable to go the other way around. The script is attached to a GameObject that is created on startup - this GameObject has other scripts attached to it which allow it to control buttons and menus in the game.
Does anybody know how I de-serialize the SaveGame Json Text and replace the script attached to the GameObject with the SaveGame? My only solution at the moment is to analyze all the text, which is really really cumbersome.
Answer by Bilelmnasser · Sep 29, 2017 at 08:11 AM
hi, first of all MonoBehaviour isn't serializable no - but that's probably a good thing. You'd be able to serialize it, but not deserialize. What we can do is use the Memento pattern - an object you have an instance of from your script which is serializable itself, which keeps all the data for the object, simply done using JsonUtility class of unity.
EDIT : Use JsonUtility to save what ever you need from a Monobehavior in your own custom class , initialize your monobehavior from your custom objects values (use awake or start function).
only thing you can do is to simply save what you need to be stored from the monobehaviour into a custom object.
[Serializable]
public class MyClass
{
public int level;
public float timeElapsed;
public string playerName;
}
// preparation of my object
MyClass myObject = new MyClass();
myObject.level = 1;
myObject.timeElapsed = 47.5f;
myObject.playerName = "Dr Charles Francis";
//serialisation process to json
//you can save that text to text file
//result : {"level":1,"timeElapsed":47.5,"playerName":"Dr Charles Francis"}
string json = JsonUtility.ToJson(myObject);
//deserialisation process from a json text
//you can load that text from a file
myObject = JsonUtility.FromJson<MyClass>(json);
The memento pattern is not necessary as Unity's JsonUtility has the FromJsonOverwrite method. So you can apply the serialized data onto an existing instance of an object. This also works for $$anonymous$$onoBehaviours where "FromJson" wouldn't work.
Ah, this is even better! Then I can overwrite the script attached to the GameObject directly?
Yes, however you only overwrite the serialized values of the component. So the component itself need exist already.
Answer by Bunny83 · Oct 02, 2017 at 12:50 PM
Ok just to give an example of what i said in my comment above. You can simply do:
public class Inventory : MonoBehaviour
{
public int Money;
public string equippedItem;
public List<string> items;
public string Save()
{
return JsonUtility.ToJson(this, true);
}
public void Load(string aJson)
{
JsonUtility.FromJsonOverwrite(aJson, this);
}
}
When calling Save you actually get a JSON representation of this monobehaviour which might look like this:
{
"Money": 1337,
"equippedItem": "FooBar",
"items": [
"Item1",
"Item2",
"Item3"
]
}
I actually just added this test code to the end of the class:
private static string save = "";
void OnGUI ()
{
if (GUILayout.Button("Save"))
{
save = Save();
}
if (GUILayout.Button("Load"))
{
Load(save);
}
save = GUILayout.TextArea(save);
}
This will allow you to "save" the current state of the class into the static "save" variable as string. The result will be displayed in a TextArea (from which i copied the above json). When you press "Load" it will do the reverse.
Note that the JsonUtility can not create MonoBehaviours, Components or GameObjects. It only supports serializing non built-in classes. So trying to serialize a "gameobject" or "transform" directly doesn't work. It will throw
ArgumentException: JsonUtility.ToJson does not support engine types.
The only exception to this rule are classes derived from MonoBehaviour or ScriptableObject. While ScriptableObjects can be created by using JsonUtilty.FromJson<type>()
that doesn't work with MonoBehaviours. For those you have to use JsonUtility.FromJsonOverwrite()
Note that the JsonUtility does support the ISerializationCallbackReceiver interface to serialize pretty much everything as long as your callbacks "transform" it into data that can be serialized by Unity.
we can do it even like this :
[serializable]
public class dataclass
{
public int $$anonymous$$oney;
public string equippedItem;
public List<string> items;
}
public class Inventory : $$anonymous$$onoBehaviour
{
public dataclass DataSave;
public string Save()
{
return JsonUtility.ToJson(this, true);
}
public void Load(string aJson)
{
JsonUtility.FromJsonOverwrite(aJson, this);
}
}