CustomTypes serialization with string
Options
Hi!
I recently had trouble trying to add a custom type containing a string to the serializable types in photon (with the CustomTypes.cs script, as explained here)
The example in the documentation does not work as it is for a string, and i had a lot of trouble finding the solution in the forums, so here is my own solution for a class with a string and int. If I missed something and there is an easier way, or even if my code is just no good, please tell !
the class to serialize:
PS : Also i don't know how to display code properly on a forum so i just copied some html from another post, but i have no idea what i am actually doing, tell me if something is wrong...
I recently had trouble trying to add a custom type containing a string to the serializable types in photon (with the CustomTypes.cs script, as explained here)
The example in the documentation does not work as it is for a string, and i had a lot of trouble finding the solution in the forums, so here is my own solution for a class with a string and int. If I missed something and there is an easier way, or even if my code is just no good, please tell !
the class to serialize:
public class CustomType { public string someString; public int someInt; }in the Register() function:
PhotonPeer.RegisterType(typeof(CustomType), (byte)'N', SerializeCustomType, DeserializeCustomType);the serialization:
private static short SerializeCustomType(StreamBuffer outStream, object customobject)=D
{
CustomType o = (CustomType)customobject;
short strLen = (short)System.Text.Encoding.UTF8.GetBytes(o.someString).Length;
byte[] bytes = new byte[2 + 4 + strLen]; //size of short (for string length) + size of int + size of the string
int index = 0;
Protocol.Serialize(strLen, bytes, ref index); // write string length to byte array
Protocol.Serialize(o.someInt, bytes, ref index); //write int to byte array
System.Array.Copy(System.Text.Encoding.UTF8.GetBytes(o.someString), 0, bytes, index, strLen); // write string
outStream.Write(bytes, 0, 2 + 4 + strLen);
return (short)(strLen + 6); // what is this return used for?
}
private static object DeserializeCustomType(StreamBuffer inStream, short length)
{
CustomType o = new CustomType();
byte[] strLenByte = new byte[2];
short strLen;
int index = 0;
inStream.Read(strLenByte, 0, 2); //read the size of the string first
Protocol.Deserialize(out strLen, strLenByte, ref index);
byte[] memCustomType = new byte[4 + strLen];
inStream.Read(memCustomType, 0, 4 + strLen);// then read the rest (the CustomType object )
index = 0;
Protocol.Deserialize(out o.someInt, memCustomType, ref index);
o.someString= System.Text.Encoding.UTF8.GetString(memCustomType, index, strLen);
return o;
}
PS : Also i don't know how to display code properly on a forum so i just copied some html from another post, but i have no idea what i am actually doing, tell me if something is wrong...
0