- Home /
The question is answered, right answer was accepted
Converting Vector3[] to byte[]
I have a similar question to:
http://answers.unity3d.com/questions/683693/converting-vector3-to-byte.html
it has a nice answer at the bottom:
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) );
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));
The main difference is...what if you want to convert 200 vector3's? how would you go about it?
By using an iteration loop, assu$$anonymous$$g you don't randomly have 200 Vector3's, if they were in an array you could just say
List<byte[]> vectorBytes = new List<byte[]>;
Vector3[] vectors;
for (int i = 0; i < vectors.Length; i++)
{
byte[] buff = new byte[sizeof(float)*3];
Buffer.BlockCopy( BitConverter.GetBytes( vectors[i].x ), 0, buff, 0*sizeof(float), sizeof(float) );
Buffer.BlockCopy( BitConverter.GetBytes( vectors[i].y ), 0, buff, 1*sizeof(float), sizeof(float) );
Buffer.BlockCopy( BitConverter.GetBytes( vectors[i].z ), 0, buff, 2*sizeof(float), sizeof(float) );
vectorBytes.Add(buff);
}
Of course if your reasoning is for serialization purposes, it would be easier to make a Position class that is serializable with 3 floats. We all dislike the fact that Unity made Vectors not serializable...
actually this is to send a chunk of vector3 information over a network and then convert back on the other side so...and I'm actually wondering how much of a difference this will make..would it be better to just send the vector3 array directly? is converting to bytes even a good idea? I'm not really sure on this.
Well no matter what, adding additional conversions will slow things down. If you can avoid ANY conversions, do so. If you can't avoid them, take the least path of resistance.
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How do I programmatically specify direction from a given vector? 1 Answer
Rotating a Vector3 in Instantiation 1 Answer