Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 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 iamhim · Apr 09, 2014 at 04:44 PM · vector3bytearraybytebytes

Converting Vector3 to Byte[]?

Hi, I'm looking for a efficient way to convert a Vector3 to a Byte[] array as I'm writing a program that'll send this Byte[] over to the server.

Currently what i have in mind is this:

 Vector3 vector = Vector3.Zero;
     
 byte[] array = new byte[3];
     
 array[0] = vector.x;
 array[1] = vector.y;
 array[2] = vector.z;

Are there any other elegant ways to do this instead?

Comment
Add comment · Show 3
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 Eric5h5 · Apr 09, 2014 at 09:12 PM 1
Share

That won't work, since a Vector3 is 3 single-precision floats, which require 4 bytes each, for a total of 12.

avatar image multimedial · Jun 05, 2015 at 08:26 AM 0
Share

Vector3 is marked as not being serializable for me (Unity5).

avatar image Cherno · Jun 05, 2015 at 03:42 PM 0
Share

You can use an ISerializationSurrogate to serialize a Vector3.

 using System.Runtime.Serialization;
 using UnityEngine;
 
 sealed class Vector3SerializationSurrogate : ISerializationSurrogate {
     
     // $$anonymous$$ethod called to serialize a Vector3 object
     public void GetObjectData(System.Object obj,
                               SerializationInfo info, Strea$$anonymous$$gContext context) {
         
         Vector3 v3 = (Vector3) obj;
         info.AddValue("x", v3.x);
         info.AddValue("y", v3.y);
         info.AddValue("z", v3.z);
         //Debug.Log(v3);
     }
     
     // $$anonymous$$ethod called to deserialize a Vector3 object
     public System.Object SetObjectData(System.Object obj,
                                        SerializationInfo info, Strea$$anonymous$$gContext 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!
     }
 }

4 Replies

· Add your reply
  • Sort: 
avatar image
3

Answer by Eric5h5 · Apr 09, 2014 at 09:11 PM

Use the BitConverter class, keeping in mind that it does not take processor endianness into account.

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 stevethorne · Apr 09, 2014 at 09:39 PM 0
Share

Is there a way to find this endianness? or is it up to whoever unpacks it on the other end?

avatar image Eric5h5 · Apr 10, 2014 at 02:36 PM 1
Share

System.BitConverter.IsLittleEndian

avatar image iamhim · Apr 10, 2014 at 03:46 PM 0
Share

can you explain on how to do it? Bitconverter.Getbytes returns a array of bytes which i can't store it in a byte[], but i need all three axis in a single byte[], or could i convert the axis into a string, send it to the server and have the server convert it back to a float? LOL

avatar image Eric5h5 · Apr 11, 2014 at 01:23 PM 1
Share

No, do not send a string. An array of bytes is byte[]. You can just copy the 3 byte arrays into a single byte array if necessary.

avatar image
3

Answer by Nanity · Apr 11, 2014 at 01:36 PM

Pure elegance with generic functions <3 Works like a charm!

http://answers.unity3d.com/questions/174207/not-able-to-pass-an-instance-of-a-class-over-a-net.html

Edit: Well I should give an example how your final code should look like with the link given:

 Vector3 vector = Vector3.Zero;
 byte[] array = InfoSender.SerializeObject(vector);

I wrote an accoriding genereic deserialize function that wasn't given in the link, very handy:

 public static _T DeserializeObject<_T>(byte[] dataStream)
 {
     MemoryStream memStr = new MemoryStream(dataStream);
     memStr.Position = 0;
     BinaryFormatter bf = new BinaryFormatter();
     bf.Binder = new VersionFixer();

     return (_T)bf.Deserialize(memStr);
 }
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 karl_jones · Jun 05, 2015 at 08:32 AM

Use BitConverter.GetBytes to convert each float (x,y,z) into bytes and put them into an array.

Something like this

 byte[] bytes = new bytes[12]; // 4 bytes per float
 
 Buffer.BlockCopy( BitConverter.GetBytes( ourVec.x ), 0, bytes, 0, 4 );
 Buffer.BlockCopy( BitConverter.GetBytes( ourVec.y ), 0, bytes, 4, 4 );
 Buffer.BlockCopy( BitConverter.GetBytes( ourVec.z ), 0, bytes, 8, 4 );

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 Idual · Nov 21, 2019 at 11:15 AM 0
Share

Am I missing something? I've just looked at the docs for Buffer.BlockCopy and the order of the arguments is different from yours. https://docs.microsoft.com/en-us/dotnet/api/system.buffer.blockcopy?view=netframework-4.8#System_Buffer_BlockCopy_System_Array_System_Int32_System_Array_System_Int32_System_Int32_

Should your example not read:

Buffer.BlockCopy(BitConverter.GetBytes( ourVec.y ), 0, bytes, 4, 4 );

avatar image Bunny83 Idual · Nov 21, 2019 at 11:26 AM 0
Share

Yes, absolutely ^^. I'm going to fix the answer. It's always a suprise that answers receive upvotes even they provide code that doesn't work

avatar image
1

Answer by archiemdiulian · Feb 05, 2017 at 09:12 AM

Convert from Vector3 to byte[] :

 byte[] buff = new byte[sizeof(float)*3];         
 Buffer.BlockCopy( BitConverter.GetBytes( vect.x ), 0, buff, 0*sizeof(float), sizeof(float) );
 Buffer.BlockCopy( BitConverter.GetBytes( vect.y ), 0, buff, 1*sizeof(float), sizeof(float) );
 Buffer.BlockCopy( BitConverter.GetBytes( vect.z ), 0, buff, 2*sizeof(float), sizeof(float) );

Convert from byte[] to Vector3:

 byte[] buff = data;
 Vector3 vect = Vector3.zero;
 vect.x = BitConverter.ToSingle(buff,0*sizeof(float));
 vect.y = BitConverter.ToSingle(buff,1*sizeof(float));
 vect.z = BitConverter.ToSingle(buff,2*sizeof(float));
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

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

30 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

Related Questions

Is there a serialization class similar to JsonUtility but for Byte Serialization. 1 Answer

Bitmaps in unity 4 Answers

Converting a float to a byte[]? Not working 2 Answers

Loading Asset Bundle from raw bytes 1 Answer

Convert Vector3 array (vector3[]) to byte array (byte[]) 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