- Home /
Photon (PUN) Type Serialization Error on RPC
I'm attempting to use photonView.RPC(...)
, but pass a custom type through as on of the param objects. I can understand that, out of the box, my custom type needs to be serialized, and I'm okay with writing a serializer, but I'm not sure how to "hook" it into whatever serialization process that occurs when photonView.RPC
is called.
Bump, there needs to be an explanation of this subject made by Photon.
Answer by tobiass · Jan 12, 2015 at 04:39 PM
As you already mentioned, to support sending any class that's not supported out of the box, you need to write 2 methods for serialization and deserialization and you need to register them with Photon. This is called Custom Types within Photon.
In PUN, you will find a class CustomTypes. This can be a blueprint for your own type support. The most important thing to take away from it are the signatures for the 2 methods and how to register.
Example for Vector2 class:
private static byte[] SerializeVector2(object customobject)
{
Vector2 vo = (Vector2)customobject;
MemoryStream ms = new MemoryStream(2 * 4);
ms.Write(BitConverter.GetBytes(vo.x), 0, 4);
ms.Write(BitConverter.GetBytes(vo.y), 0, 4);
return ms.ToArray();
}
private static object DeserializeVector2(byte[] bytes)
{
Vector2 vo = new Vector2();
vo.x = BitConverter.ToSingle(bytes, 0);
vo.y = BitConverter.ToSingle(bytes, 4);
return vo;
}
And register those 2 in some Awake() method somewhere like so:
PhotonPeer.RegisterType(typeof(Vector2), (byte)'W', SerializeVector2, DeserializeVector2);
The 'W' will be the type-shorthand and must be different per type. Of course, your own class will have some different content and name and another shorthand. Make extra sure you write as many bytes into the byte[] as you read (and vice versus). You can use the BitConverter or any other means to write the byte[].
Keep in mind that in the network messages, a Custom Type will be wrapped in another 4 bytes. Due to that, it does not make sense to write a custom type for just 1..2 bytes. In that case, you can better send a byte or short value and use it accordingly to the type you expect (cast, etc).
Take a look at CustomTypes.cs to find out which Unity types are supported. The player does not need to be sent in many cases...
Answer by specterdragon · Jan 18, 2014 at 10:35 PM
I'm currently trying to find the same answer for a custom class. Don't mind creating a custom serializer, but not sure where to start. Strings, arrays, hashes - all OK. PhotonPlayer - not sure about that one.
Your answer
Follow this Question
Related Questions
Photon Network Instantiate Objects over Network 1 Answer
Multiplayer Position Sychronization problem in unity2d 1 Answer
Very Strange RPC error 1 Answer
Destroying the bullet over a photon network 4 Answers
RPC return value 1 Answer