• 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
4
Question by Arelius · Jan 06, 2014 at 10:26 AM · serializationunity 4.2

Unity system.object serialization.

I have a object, that contains something of type system.object.

 public class Foo : MonoBehaviour
 {
   [SerializeField]
   object Val;
 }

Val can contain primitives such as a float, a Vector3 or a Color.

Is there any way to get this to serialize properly?

Comment
Add comment · Show 2
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 DreamingSpirit · Oct 20, 2014 at 11:53 PM 0
Share

Is anyone aware of a solution for this? Is it possible to use custom serialization or somehow cast it to its real type on serialization?

avatar image Bunny83 · Oct 21, 2014 at 01:08 AM 0
Share

@Drea$$anonymous$$gSpirit: Check out my answer below ;)

1 Reply

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

Answer by Bunny83 · Oct 21, 2014 at 12:03 AM

Not without some extra fields which can actually store a supported serialized type. Unity serializes data based on the variable type. Since System.Object isn't a supported type it won't get serialized at all.

The best bet here would be to use the new ISerializationCallbackReceiver paired with a serialized string variable which holds the serialized data. How you serialize and deserialize your "object" is up to you as long as you can convert it into a string and be able to recreate the original value from that string you should be fine.

Here's an (untested) example to support int, float, Color and Vector3 values:

 public class Foo : MonoBehaviour, ISerializationCallbackReceiver
 {
     // our value of interest
     private object val;
     
     [SerializeField, HideInInspector]
     private string valSerialized;
     
     public void OnBeforeSerialize()
     {
         if (val == null)
         {
             valSerialized = "n";
             return;
         }
         var type = val.GetType();
         if (type == typeof(int))
             valSerialized = "i"+val.ToString();
         else if (type == typeof(float))
             valSerialized = "f"+val.ToString();
         else if (type == typeof(Color))
         {
             Color32 c = (Color)val;
             uint v = (uint)c.r + (uint)c.g<<8 + (uint)c.b<<16 + (uint)c.a<<24;
             valSerialized = "c" + v;
         }
         else if (type == typeof(Vector3))
         {
             Vector3 v = (Vector3)val;
             valSerialized = "v" + v.x + "|" +v.y + "|" + v.z;
         }
     }
     
     public void OnAfterDeserialize()
     {
         if (valSerialized.Length == 0)
             return;
         char type = valSerialized[0];
         if (type == 'n')
             val = null;
         else if (type == 'i')
             val = int.Parse(valSerialized.SubString(1));
         else if (type == 'f')
             val = float.Parse(valSerialized.SubString(1));
         else if (type == 'c')
         {
             uint v = int.Parse(valSerialized.SubString(1));
             Color c = new Color32(v & 0xFF, (v>>8) & 0xFF, (v>>16) & 0xFF,(v>>24) & 0xFF);
             val = c;
         }
         else if (type == 'v')
         {
             string[] v = valSerialized.SubString(1).Split('|');
             val = new Vector3(float.Parse(v[0]), float.Parse(v[1]), float.Parse(v[2]));
         }
     }
 }

Note: The deserialization has no checks if the string is in the required format. To actually use this you might want to implement some checks or at least enclose it in a try-catch block.

Comment
Add comment · Show 2 · 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 GTallig · Feb 21, 2017 at 10:05 AM 1
Share

$$anonymous$$aybe, a little addition: If your instance of val is of any type, which is supported by the unity serializer, you could just use JsonUtility.ToJson(val) and JsonUtility.FromJson(valSerialized, typeof(YourType)) to serialize and deserialize to and from strings. That makes it a little bit easier ;)

avatar image tribaleur GTallig · Apr 30, 2020 at 06:13 PM 0
Share

JsonUtility doesn't works with primitive Type. See : https://docs.unity3d.com/$$anonymous$$anual/JSONSerialization.html

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.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

22 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

Related Questions

Serialized data show information after load 0 Answers

Is "enum x : UInt32" cast to "enum x : int" when serializing? 1 Answer

Scriptable Object Custom Editor Not Updating 1 Answer

Unity 4.2 - adding to a Vector2 is broken??? 1 Answer

Facebook SDK - FB.Init throws AuthTokenNullException on Android 1 Answer


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