Understanding and using RPCs in Unity

The RPC concept in Unity took me quite a while to get used to. I think the most important thing to understand is that each Method with the [RPC] Attribute has to be unique in the scene. If it is not random instances will get called and you will go mad. Here are some common mistakes:

Example 2

Example 1

You probably are saying that you can not use the Unity networking then, because it is normal to have multiple instances of one script in one scene and you want to call just the right instance. But don’t be afraid i am showing you the solution i came up with:

Solution Part 1

Solution Part 2

The Concept here is quite simple. I have NetworkComponent, which i use instead of Monobehaviour if i want to have a script which is supposed to be called over the network. All this component does is to assign a NetworkView to it when you add it in a scene. And set it to be observed and turn of state synchronization which is not needed. Then instead of calling the Method itself, i created a class called RPCExtended, which basicly handles all communication between components. I then call the public available method in RPCExtended, which will then search for the correct object and call the method there. The problem is that you will need to write alot of code this way. I fixed this by creating methods which can call any method with one kind of parameters, therefor i needed the help of reflection:

Solution Part 3

This solution is more friendly for us coders but transmits more data because the MethodName is send as well. How it works is easy, we always send as the first parameter the MethodName and we call the method inside the object. I use this kind of method for methods that are not called often.The overloads of the method let you call a method with any signature you support.

One last thing i want to mention. If you want to send complete object you can achieve this via serializing the object to a string and then sending the data. I would not recommend this though because it is using up quite some bandwith.

One thought on “Understanding and using RPCs in Unity

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s