Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
13 Jun 22 - 14 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
11
Question by Conan Morris · Apr 28, 2015 at 07:55 PM · quaternionserialize

Serialize Quaternion or Vector3

It seems like saving your players location and rotation would be pretty common, but I can't seem to find any example of serializing a Quaternion or Vectory3 anywhere.

According to the unity docs here it says the both are serializable but I keep getting the following error "SerializationException: Type UnityEngine.Quaternion is not marked as Serializable." when trying to serialize the following class.

 [Serializable]
 public class Entity{
     public string entityName;
     public Quaternion entityRotation;
 }


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 Bunny83 · Apr 28, 2015 at 08:02 PM 0
Share

What exactly do you mean by serialize? Do you mean "let Unity serialize the class" or do you mean you tried to serialize the class with .NET's / mono's serialization system?

$$anonymous$$ore context please.

I guess that you try to manually serialize it. In this case, no, it's not compatible with .NET / mono serialization. You have to implement ISerializable and provide a custom serialization method. I'l post an answer ^^

avatar image Conan Morris · Apr 29, 2015 at 04:31 PM 0
Share

Thanks for the responses. I was hoping I didn't have to manually do this and was just missing something simple in Unity that would automatically serialize these objects.

11 Replies

· Add your reply
  • Sort: 
avatar image
30

Answer by Cherno · Apr 28, 2015 at 11:46 PM

Here are serializable versions of the Vector3 and Quaternion class, with automatic conversion:

 using UnityEngine;
 using System;
 using System.Collections;
 
 /// <summary>
 /// Since unity doesn't flag the Vector3 as serializable, we
 /// need to create our own version. This one will automatically convert
 /// between Vector3 and SerializableVector3
 /// </summary>
 [System.Serializable]
 public struct SerializableVector3
 {
     /// <summary>
     /// x component
     /// </summary>
     public float x;
     
     /// <summary>
     /// y component
     /// </summary>
     public float y;
     
     /// <summary>
     /// z component
     /// </summary>
     public float z;
     
     /// <summary>
     /// Constructor
     /// </summary>
     /// <param name="rX"></param>
     /// <param name="rY"></param>
     /// <param name="rZ"></param>
     public SerializableVector3(float rX, float rY, float rZ)
     {
         x = rX;
         y = rY;
         z = rZ;
     }
     
     /// <summary>
     /// Returns a string representation of the object
     /// </summary>
     /// <returns></returns>
     public override string ToString()
     {
         return String.Format("[{0}, {1}, {2}]", x, y, z);
     }
     
     /// <summary>
     /// Automatic conversion from SerializableVector3 to Vector3
     /// </summary>
     /// <param name="rValue"></param>
     /// <returns></returns>
     public static implicit operator Vector3(SerializableVector3 rValue)
     {
         return new Vector3(rValue.x, rValue.y, rValue.z);
     }
     
     /// <summary>
     /// Automatic conversion from Vector3 to SerializableVector3
     /// </summary>
     /// <param name="rValue"></param>
     /// <returns></returns>
     public static implicit operator SerializableVector3(Vector3 rValue)
     {
         return new SerializableVector3(rValue.x, rValue.y, rValue.z);
     }
 }


Quaternion:

 using UnityEngine;
 using System;
 using System.Collections;
 
 /// <summary>
 /// Since unity doesn't flag the Quaternion as serializable, we
 /// need to create our own version. This one will automatically convert
 /// between Quaternion and SerializableQuaternion
 /// </summary>
 [System.Serializable]
 public struct SerializableQuaternion
 {
     /// <summary>
     /// x component
     /// </summary>
     public float x;
     
     /// <summary>
     /// y component
     /// </summary>
     public float y;
     
     /// <summary>
     /// z component
     /// </summary>
     public float z;
     
     /// <summary>
     /// w component
     /// </summary>
     public float w;
     
     /// <summary>
     /// Constructor
     /// </summary>
     /// <param name="rX"></param>
     /// <param name="rY"></param>
     /// <param name="rZ"></param>
     /// <param name="rW"></param>
     public SerializableQuaternion(float rX, float rY, float rZ, float rW)
     {
         x = rX;
         y = rY;
         z = rZ;
         w = rW;
     }
     
     /// <summary>
     /// Returns a string representation of the object
     /// </summary>
     /// <returns></returns>
     public override string ToString()
     {
         return String.Format("[{0}, {1}, {2}, {3}]", x, y, z, w);
     }
     
     /// <summary>
     /// Automatic conversion from SerializableQuaternion to Quaternion
     /// </summary>
     /// <param name="rValue"></param>
     /// <returns></returns>
     public static implicit operator Quaternion(SerializableQuaternion rValue)
     {
         return new Quaternion(rValue.x, rValue.y, rValue.z, rValue.w);
     }
     
     /// <summary>
     /// Automatic conversion from Quaternion to SerializableQuaternion
     /// </summary>
     /// <param name="rValue"></param>
     /// <returns></returns>
     public static implicit operator SerializableQuaternion(Quaternion rValue)
     {
         return new SerializableQuaternion(rValue.x, rValue.y, rValue.z, rValue.w);
     }
 }

Also check out this guide to Surrogates, very useful:

Link

Here is a ISerializationSurrogate for Vector3:

 using System.Runtime.Serialization;
 using UnityEngine;
 
 sealed class Vector3SerializationSurrogate : ISerializationSurrogate {
     
     // Method called to serialize a Vector3 object
     public void GetObjectData(System.Object obj,
                               SerializationInfo info, StreamingContext context) {
         
         Vector3 v3 = (Vector3) obj;
         info.AddValue("x", v3.x);
         info.AddValue("y", v3.y);
         info.AddValue("z", v3.z);
         Debug.Log(v3);
     }
     
     // Method called to deserialize a Vector3 object
     public System.Object SetObjectData(System.Object obj,
                                        SerializationInfo info, StreamingContext context,
                                        ISurrogateSelector selector) {
         
         Vector3 v3 = (Vector3) obj;
         v3.x = (float)info.GetValue("x", typeof(float));
         v3.y = (float)info.GetValue("y", typeof(float));
         v3.z = (float)info.GetValue("z", typeof(float));
         obj = v3;
         return obj;   // Formatters ignore this return value //Seems to have been fixed!
     }
 }

You can include the Surrogate in your formatter like this:

 BinaryFormatter bf = new BinaryFormatter();
 
         // 1. Construct a SurrogateSelector object
         SurrogateSelector ss = new SurrogateSelector();
         
         Vector3SerializationSurrogate v3ss = new Vector3SerializationSurrogate();
         ss.AddSurrogate(typeof(Vector3), 
                         new StreamingContext(StreamingContextStates.All), 
                         v3ss);
         
         // 2. Have the formatter use our surrogate selector
         bf.SurrogateSelector = ss;


Comment
Add comment · Show 8 · 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 marsonmao · Aug 11, 2015 at 03:40 AM 0
Share

Why the hell are Vector3 and Quaternion of Unity non-serializable?!

avatar image Cherno · Aug 11, 2015 at 09:19 AM 0
Share

^ What? Double negative much?

avatar image marsonmao · Aug 20, 2015 at 03:49 AM 0
Share

@Cherno lol didn't notice that, fixed, thanks

avatar image Cherno · Aug 20, 2015 at 06:36 AM 1
Share

All of the Unity-specific classes are non-serializable. Check the comments under the OP, where the differences between Unity and .NET serialization are explained.

avatar image BastiaanGrisel · Jul 06, 2017 at 10:30 AM 0
Share

Thanks! Just what I needed :D

Show more comments
avatar image
3

Answer by Voxel-Busters · Aug 07, 2015 at 12:03 PM

You won't be able to serialise Vectors, Colors and Quaternions directly as they are not Serializable classes. But c# allows you to implement serialization extensions classes using ISerializationSurrogate. Check this link for more info https://msdn.microsoft.com/en-us/library/system.runtime.serialization.surrogateselector%28v=vs.110%29.aspx

But if you want to avoid all the trouble and save time, then check out Cross Platform Easy Save fast and efficient plugin designed to handle serialization of c# class object as well Unity Objects like GameObject, Transform, Textures etc.

You can have a look at complete Scene Serialization over here

Comment
Add comment · 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
3

Answer by JimmyCushnie · Dec 13, 2018 at 09:19 AM

About a year ago, when I barely knew how to code, I copied @Cherno 's code for the SerializableVector3 and SerializableQuaternion structs. Since then I've improved the code, and I thought I'd post it here in case it's helpful to someone else. Here are my changes:

  • removed a ton of useless s

  • improve code formatting so that it's neater and more readable

  • renamed a bunch of stuff, including the classes themselves; they're called SVector3 and SQuaternion now, which is much nicer to use

  • added +, -, * and / operators to SerializableVector3

  • added SColor32 class

And here's the code:

 namespace SerializableTypes
 {
     /// <summary> Serializable version of UnityEngine.Vector3. </summary>
     [Serializable]
     public struct SVector3
     {
         public float x;
         public float y;
         public float z;
 
         public SVector3(float x, float y, float z)
         {
             this.x = x;
             this.y = y;
             this.z = z;
         }
 
         public override string ToString()
             => $"[x, y, z]";
 
         public static implicit operator Vector3(SVector3 s)
             => new Vector3(s.x, s.y, s.z);
 
         public static implicit operator SVector3(Vector3 v)
             => new SVector3(v.x, v.y, v.z);
 
 
         public static SVector3 operator +(SVector3 a, SVector3 b) 
             => new SVector3(a.x + b.x, a.y + b.y, a.z + b.z);
 
         public static SVector3 operator -(SVector3 a, SVector3 b)
             => new SVector3(a.x - b.x, a.y - b.y, a.z - b.z);
 
         public static SVector3 operator -(SVector3 a)
             => new SVector3(-a.x, -a.y, -a.z);
 
         public static SVector3 operator *(SVector3 a, float m)
             => new SVector3(a.x * m, a.y * m, a.z * m);
 
         public static SVector3 operator *(float m, SVector3 a)
             => new SVector3(a.x * m, a.y * m, a.z * m);
 
         public static SVector3 operator /(SVector3 a, float d)
             => new SVector3(a.x / d, a.y / d, a.z / d);
     }
 
     /// <summary> Serializable version of UnityEngine.Quaternion. </summary>
     [Serializable]
     public struct SQuaternion
     {
         public float x;
         public float y;
         public float z;
         public float w;
 
         public SQuaternion(float x, float y, float z, float w)
         {
             this.x = x;
             this.y = y;
             this.z = z;
             this.w = w;
         }
 
         public override string ToString()
             => $"[{x}, {y}, {z}, {w}]";
 
         public static implicit operator Quaternion(SQuaternion s)
             => new Quaternion(s.x, s.y, s.z, s.w);
 
         public static implicit operator SQuaternion(Quaternion q)
             => new SQuaternion(q.x, q.y, q.z, q.w);
     }
 
     /// <summary> Serializable version of UnityEngine.Color32 without transparency. </summary>
     [Serializable]
     public struct SColor32
     {
         public byte r;
         public byte g;
         public byte b;
 
         public SColor32(byte r, byte g, byte b)
         {
             this.r = r;
             this.g = g;
             this.b = b;
         }
 
         public SColor32(Color32 c)
         {
             r = c.r;
             g = c.g;
             b = c.b;
         }
 
         public override string ToString()
             => $"[{r}, {g}, {b}]";
 
         public static implicit operator Color32(SColor32 rValue)
             => new Color32(rValue.r, rValue.g, rValue.b, a: byte.MaxValue);
 
         public static implicit operator SColor32(Color32 rValue)
             => new SColor32(rValue.r, rValue.g, rValue.b);
     }
 }

If you want to make your own serializable versions of Unity structs - i.e. Color, Vector2, Vector3Int, ect - the Unity C# Reference is a great resource. You can find the full Unity source code for the struct you need.

Comment
Add comment · 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
1

Answer by aeroson · Jan 04, 2016 at 11:34 AM

Iam using the epic free https://github.com/jacobdufault/fullserializer

Comment
Add comment · 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
0

Answer by Bunny83 · Apr 28, 2015 at 08:09 PM

In case you talk about .NET / mono serialization you have to implement the ISerializable interface like this:

 using System.Runtime.Serialization;
 
 public class Entity : ISerializable
 {
     public string entityName;
     public Quaternion entityRotation;
 
     public Entity(SerializationInfo info, StreamingContext context)
     {
         entityName = info.GetString("name");
         entityRotation.x = info.GetSingle("RotationX");
         entityRotation.y = info.GetSingle("RotationY");
         entityRotation.z = info.GetSingle("RotationZ");
         entityRotation.w = info.GetSingle("RotationW");
     }
 
     public void GetObjectData(SerializationInfo info, StreamingContext context)
     {
         info.AddValue("name", entityName);
         info.AddValue("RotationX", entityRotation.x);
         info.AddValue("RotationY", entityRotation.y);
         info.AddValue("RotationZ", entityRotation.z);
         info.AddValue("RotationW", entityRotation.w);
     }
 }
Comment
Add comment · 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
  • 1
  • 2
  • 3
  • ›

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

17 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

Related Questions

How can i serialize a Quaternion? 4 Answers

slow rotation over time? 1 Answer

Clamp Quaternions Rotation for camera 1 Answer

Rotate Player to Match Surface Normal While Still Maintaining Y Rotation 0 Answers

How do I find the correct speed when using Vector3.MoveTowards and Quaternion.RotateTowards together? 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