Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by squeegene · Sep 29, 2017 at 05:01 AM · classjsonserializeserializedobject

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.

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

2 Replies

· Add your reply
  • Sort: 
avatar image
3
Best Answer

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);
 
 


Comment
Add comment · Show 4 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image squeegene · Sep 30, 2017 at 06:34 AM 1
Share

Thank you! Really helpful

avatar image Bunny83 · Sep 30, 2017 at 09:57 AM 1
Share

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.

avatar image squeegene Bunny83 · Sep 30, 2017 at 07:07 PM 1
Share

Ah, this is even better! Then I can overwrite the script attached to the GameObject directly?

avatar image Bunny83 squeegene · Oct 01, 2017 at 12:47 PM 1
Share

Yes, however you only overwrite the serialized values of the component. So the component itself need exist already.

avatar image
2

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.

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Bilelmnasser · Oct 02, 2017 at 02:09 PM 0
Share

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);
      }
  }

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

70 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Cannot edit values of Class when created using .JSON file 1 Answer

change value of prefab field in a array of prefabs 0 Answers

How can I access this class from another script? 1 Answer

Generate Json from Class Type List 1 Answer

Default Serialization Values Not Being Set 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges