PUN and Photon Realtime C# SDKs provide a set of callback interfaces that you can implement in your classes:
IConnectionCallbacks: connection related callbacks.
IInRoomCallbacks: callbacks that happen inside the room.
ILobbyCallbacks: lobby related callbacks.
IMatchmakingCallbacks: matchmaking related callbacks.
IOnEventCallback: a single callback for any received event. This is 'equivalent' to the C# event
IWebRpcCallback: a single callback for receiving WebRPC operation response.
IPunInstantiateMagicCallback: a single callback for instantiated PUN prefabs.
IPunObservable: PhotonView serialization callbacks.
IPunOwnershipCallbacks: PUN ownership transfer callbacks.
You can implement one or more interfaces per class. You can also implement the same interface by more than one class. The price to pay is that classes that implement these interfaces may become too long or have unused methods.
All callback interfaces except
IPunInstantiateMagicCallback must be registered and unregistered.
For example in Unity, you could use the
Implementing these interfaces is optional but recommended as we think it can make your code more readable and maintainable. It also makes the Photon flow and states easier to manage by providing the exact timing to execute some logic. Other alternatives may require usage of state flags fields, polling to check client networking state or subscribing to all netwroking client's status changes or recevied events or operation responses. This requires deep knoweldege about some internals or low level Photon details, which you can avoid and focus on your game.
The reasons behind choosing interfaces over other ways of implementing a callbacks system:
- making sure callbacks' methods signatures are respected which is guaranteed by the compiler when implementing interfaces
- grouping callbacks logically related into a single class
- compared to other methods of providing callbacks, it has less garbage overhead and avoids memory leaks
MonoBehaviourPunCallbacks class is the easiest and fastest way to implement PUN2 callbacks:
- it's a
MonoBehaviourthat allows you to selectively override the callbacks you need and only those you need
- no need to remember all the callbacks' interfaces as it implements most of them:
- it already handles callbacks registration and deregistration on your behalf (respectively in
- it extends
MonoBehaviourPunwhich exposes the PhotonView easily in a property if the latter is attached to the same GameObject
However, you should be careful as:
- it does not implement all callbacks interfaces but most. It does not implement
IPunOwnershipCallbacks. PUN2's utility interfaces are also not implemented e.g.
- if you extend
MonoBehaviourPunCallbacksmake sure to call the base class methods if you override
MonoBehaviourPunCallbacks.photonViewwill be null (and useless) if the component is not attached to the same GameObject as a PhotonView