Photon Unity Networking 2: PhotonNetwork Class Reference

Photon Unity Networking 2

The main class to use the PhotonNetwork plugin. This class is static. More...

Static Public Member Functions

static bool ConnectUsingSettings ()
 Connect to Photon as configured in the PhotonServerSettings file. More...
 
static bool ConnectToMaster (string masterServerAddress, int port, string appID)
 Connect to a Photon Master Server by address, port, appID. More...
 
static bool ConnectToBestCloudServer ()
 Connect to the Photon Cloud region with the lowest ping (on platforms that support Unity's Ping). More...
 
static bool ConnectToRegion (string region)
 Connects to the Photon Cloud region of choice. More...
 
static void Disconnect ()
 Makes this client disconnect from the photon server, a process that leaves any room and calls OnDisconnected on completion. More...
 
static bool Reconnect ()
 Can be used to reconnect to the master server after a disconnect. More...
 
static void NetworkStatisticsReset ()
 Resets the traffic stats and re-enables them. More...
 
static string NetworkStatisticsToString ()
 Only available when NetworkStatisticsEnabled was used to gather some stats. More...
 
static int GetPing ()
 The current roundtrip time to the photon server. More...
 
static void FetchServerTimestamp ()
 Refreshes the server timestamp (async operation, takes a roundtrip). More...
 
static void SendAllOutgoingCommands ()
 Can be used to immediately send the RPCs and Instantiates just called, so they are on their way to the other players. More...
 
static bool CloseConnection (Player kickPlayer)
 Request a client to disconnect (KICK). Only the master client can do this More...
 
static bool SetMasterClient (Player masterClientPlayer)
 Asks the server to assign another player as Master Client of your current room. More...
 
static bool JoinRandomRoom ()
 Joins a random room that matches the filter. Will callback: OnJoinedRoom or OnJoinRandomFailed. More...
 
static bool JoinRandomRoom (Hashtable expectedCustomRoomProperties, byte expectedMaxPlayers)
 Joins a random room that matches the filter. Will callback: OnJoinedRoom or OnJoinRandomFailed. More...
 
static bool JoinRandomRoom (Hashtable expectedCustomRoomProperties, byte expectedMaxPlayers, MatchmakingMode matchingType, TypedLobby typedLobby, string sqlLobbyFilter, string[] expectedUsers=null)
 Joins a random room that matches the filter. Will callback: OnJoinedRoom or OnJoinRandomFailed. More...
 
static bool CreateRoom (string roomName, RoomOptions roomOptions=null, TypedLobby typedLobby=null, string[] expectedUsers=null)
 Creates a new room. Will callback: OnCreatedRoom and OnJoinedRoom or OnCreateRoomFailed. More...
 
static bool JoinOrCreateRoom (string roomName, RoomOptions roomOptions, TypedLobby typedLobby, string[] expectedUsers=null)
 Joins a specific room by name and creates it on demand. Will callback: OnJoinedRoom or OnJoinRoomFailed. More...
 
static bool JoinRoom (string roomName, string[] expectedUsers=null)
 Joins a room by name. Will callback: OnJoinedRoom or OnJoinRoomFailed. More...
 
static bool RejoinRoom (string roomName)
 Rejoins a room by roomName (using the userID internally to return). Will callback: OnJoinedRoom or OnJoinRoomFailed. More...
 
static bool ReconnectAndRejoin ()
 When the client lost connection during gameplay, this method attempts to reconnect and rejoin the room. More...
 
static bool LeaveRoom (bool becomeInactive=true)
 Leave the current room and return to the Master Server where you can join or create rooms (see remarks). More...
 
static bool JoinLobby ()
 On MasterServer this joins the default lobby which list rooms currently in use. More...
 
static bool JoinLobby (TypedLobby typedLobby)
 On a Master Server you can join a lobby to get lists of available rooms. More...
 
static bool LeaveLobby ()
 Leave a lobby to stop getting updates about available rooms. More...
 
static bool FindFriends (string[] friendsToFind)
 Requests the rooms and online status for a list of friends and saves the result in PhotonNetwork.Friends. More...
 
static bool GetCustomRoomList (TypedLobby typedLobby, string sqlLobbyFilter)
 Fetches a custom list of games from the server, matching a SQL-like "where" clause, then triggers OnRoomListUpdate callback. More...
 
static void SetPlayerCustomProperties (Hashtable customProperties)
 Sets this (local) player's properties and synchronizes them to the other players (don't modify them directly). More...
 
static void RemovePlayerCustomProperties (string[] customPropertiesToDelete)
 Locally removes Custom Properties of "this" player. Important: This does not synchronize the change! Useful when you switch rooms. More...
 
static bool RaiseEvent (byte eventCode, object eventContent, RaiseEventOptions raiseEventOptions, SendOptions sendOptions)
 Sends fully customizable events in a room. Events consist of at least an EventCode (0..199) and can have content. More...
 
static bool AllocateViewID (PhotonView view)
 Allocates a viewID for the current/local player. More...
 
static bool AllocateSceneViewID (PhotonView view)
 Enables the Master Client to allocate a viewID that is valid for scene objects. More...
 
static GameObject Instantiate (string prefabName, Vector3 position, Quaternion rotation, byte group=0, object[] data=null)
 
static GameObject InstantiateSceneObject (string prefabName, Vector3 position, Quaternion rotation, byte group=0, object[] data=null)
 
static void Destroy (PhotonView targetView)
 Network-Destroy the GameObject associated with the PhotonView, unless the PhotonView is static or not under this client's control. More...
 
static void Destroy (GameObject targetGo)
 Network-Destroy the GameObject, unless it is static or not under this client's control. More...
 
static void DestroyPlayerObjects (Player targetPlayer)
 Network-Destroy all GameObjects, PhotonViews and their RPCs of targetPlayer. Can only be called on local player (for "self") or Master Client (for anyone). More...
 
static void DestroyPlayerObjects (int targetPlayerId)
 Network-Destroy all GameObjects, PhotonViews and their RPCs of this player (by ID). Can only be called on local player (for "self") or Master Client (for anyone). More...
 
static void DestroyAll ()
 Network-Destroy all GameObjects, PhotonViews and their RPCs in the room. Removes anything buffered from the server. Can only be called by Master Client (for anyone). More...
 
static void RemoveRPCs (Player targetPlayer)
 Remove all buffered RPCs from server that were sent by targetPlayer. Can only be called on local player (for "self") or Master Client (for anyone). More...
 
static void RemoveRPCs (PhotonView targetPhotonView)
 Remove all buffered RPCs from server that were sent via targetPhotonView. The Master Client and the owner of the targetPhotonView may call this. More...
 
static HashSet< GameObject > FindGameObjectsWithComponent (Type type)
 Finds the GameObjects with Components of a specific type (using FindObjectsOfType). More...
 
static void SetInterestGroups (byte group, bool enabled)
 Enable/disable receiving events from a given Interest Group. More...
 
static void LoadLevel (int levelNumber)
 This method wraps loading a level asynchronously and pausing network messages during the process. More...
 
static void LoadLevel (string levelName)
 This method wraps loading a level asynchronously and pausing network messages during the process. More...
 
static bool WebRpc (string name, object parameters, bool sendAuthCookie=false)
 This operation makes Photon call your custom web-service by name (path) with the given parameters. More...
 
static void AddCallbackTarget (object target)
 Registers an object for callbacks for the implemented callback-interfaces. More...
 
static void RemoveCallbackTarget (object target)
 Removes the target object from callbacks for its implemented callback-interfaces. More...
 
static void DestroyPlayerObjects (int playerId, bool localOnly)
 Destroys all Instantiates and RPCs locally and (if not localOnly) sends EvDestroy(player) and clears related events in the server buffer. More...
 
static void DestroyAll (bool localOnly)
 
static bool LocalCleanPhotonView (PhotonView view)
 
static PhotonView GetPhotonView (int viewID)
 
static void RegisterPhotonView (PhotonView netView)
 
static void OpCleanActorRpcBuffer (int actorNumber)
 Removes the RPCs of someone else (to be used as master). This won't clean any local caches. It just tells the server to forget a player's RPCs and instantiates. More...
 
static void OpRemoveCompleteCacheOfPlayer (int actorNumber)
 Instead removing RPCs or Instantiates, this removed everything cached by the actor. More...
 
static void OpRemoveCompleteCache ()
 
static void CleanRpcBufferIfMine (PhotonView view)
 
static void OpCleanRpcBuffer (PhotonView view)
 Cleans server RPCs for PhotonView (without any further checks). More...
 
static void RemoveRPCsInGroup (int group)
 Remove all buffered RPCs from server that were sent in the targetGroup, if this is the Master Client or if this controls the individual PhotonView. More...
 
static void SetLevelPrefix (byte prefix)
 Sets level prefix for PhotonViews instantiated later on. Don't set it if you need only one! More...
 
static void SetInterestGroups (byte[] disableGroups, byte[] enableGroups)
 Enable/disable receiving on given Interest Groups (applied to PhotonViews). More...
 
static void SetSendingEnabled (byte group, bool enabled)
 Enable/disable sending on given group (applied to PhotonViews) More...
 
static void SetSendingEnabled (byte[] disableGroups, byte[] enableGroups)
 Enable/disable sending on given groups (applied to PhotonViews) More...
 

Public Attributes

const string PunVersion = "2.12"
 Version number of PUN. Used in the AppVersion, which separates your playerbase in matchmaking. More...
 
const int SyncViewId = 0
 
const int SyncCompressed = 1
 
const int SyncNullValues = 2
 
const int SyncFirstValue = 3
 

Static Public Attributes

static LoadBalancingClient NetworkingClient
 The LoadBalancingClient is part of Photon Realtime and wraps up multiple servers and states for PUN. More...
 
static readonly int MAX_VIEW_IDS = 1000
 The maximum number of assigned PhotonViews per player (or scene). See the General Documentation topic "Limitations" on how to raise this limitation. More...
 
static ServerSettings PhotonServerSettings = (ServerSettings)Resources.Load(PhotonNetwork.ServerSettingsFileName, typeof(ServerSettings))
 Serialized server settings, written by the Setup Wizard for use in ConnectUsingSettings. More...
 
static ConnectMethod ConnectMethod = ConnectMethod.NotCalled
 Tracks, which Connect method was called last. More...
 
static PunLogLevel LogLevel = PunLogLevel.ErrorsOnly
 Controls how verbose PUN is. More...
 
static float PrecisionForVectorSynchronization = 0.000099f
 The minimum difference that a Vector2 or Vector3(e.g. a transforms rotation) needs to change before we send it via a PhotonView's OnSerialize/ObservingComponent. More...
 
static float PrecisionForQuaternionSynchronization = 1.0f
 The minimum angle that a rotation needs to change before we send it via a PhotonView's OnSerialize/ObservingComponent. More...
 
static float PrecisionForFloatSynchronization = 0.01f
 The minimum difference between floats before we send it via a PhotonView's OnSerialize/ObservingComponent. More...
 
static bool UseRpcMonoBehaviourCache
 While enabled, the MonoBehaviours on which we call RPCs are cached, avoiding costly GetComponents<MonoBehaviour>() calls. More...
 
static int ObjectsInOneUpdate = 10
 Defines how many OnPhotonSerialize()-calls might get summarized in one message. More...
 

Properties

static string GameVersion [get, set]
 Version number of your game. Setting this updates the AppVersion, which separates your playerbase in matchmaking. More...
 
static string AppVersion [get]
 Sent to Photon Server to specifiy the "Virtual AppId". More...
 
static string ServerAddress [get]
 Currently used server address (no matter if master or game server). More...
 
static string CloudRegion [get]
 Currently used Cloud Region (if any). As long as the client is not on a Master Server or Game Server, the region is not yet defined. More...
 
static string BestRegionSummaryInPreferences [get, set]
 Used to store and access the "Best Region Summary" in the Player Preferences. More...
 
static bool IsConnected [get]
 False until you connected to Photon initially. True in offline mode, while connected to any server and even while switching servers. More...
 
static bool IsConnectedAndReady [get]
 A refined version of connected which is true only if your connection to the server is ready to accept operations like join, leave, etc. More...
 
static ClientState NetworkClientState [get]
 Directly provides the network-level client state, unless in OfflineMode. More...
 
static ServerConnection Server [get]
 The server (type) this client is currently connected or connecting to. More...
 
static AuthenticationValues AuthValues [get, set]
 A user's authentication values used during connect. More...
 
static TypedLobby CurrentLobby [get]
 The lobby that will be used when PUN joins a lobby or creates a game. This is defined when joining a lobby or creating rooms More...
 
static Room CurrentRoom [get]
 Get the room we're currently in (also when in OfflineMode). Null if we aren't in any room. More...
 
static Player LocalPlayer [get]
 This client's Player instance is always available, unless the app shuts down. More...
 
static string NickName [get, set]
 Set to synchronize the player's nickname with everyone in the room(s) you enter. This sets PhotonNetwork.player.NickName. More...
 
static Player[] PlayerList [get]
 A sorted copy of the players-list of the current room. This is using Linq, so better cache this value. Update when players join / leave. More...
 
static Player[] PlayerListOthers [get]
 A sorted copy of the players-list of the current room, excluding this client. This is using Linq, so better cache this value. Update when players join / leave. More...
 
static bool OfflineMode [get, set]
 Offline mode can be set to re-use your multiplayer code in singleplayer game modes. When this is on PhotonNetwork will not create any connections and there is near to no overhead. Mostly usefull for reusing RPC's and PhotonNetwork.Instantiate More...
 
static bool AutomaticallySyncScene [get, set]
 Defines if all clients in a room should automatically load the same level as the Master Client. More...
 
static bool EnableLobbyStatistics [get]
 If enabled, the client will get a list of available lobbies from the Master Server. More...
 
static bool InLobby [get]
 True while this client is in a lobby. More...
 
static int SendRate [get, set]
 Defines how many times per second PhotonNetwork should send a package. If you change this, do not forget to also change 'SerializationRate'. More...
 
static int SerializationRate [get, set]
 Defines how many times per second OnPhotonSerialize should be called on PhotonViews. More...
 
static bool IsMessageQueueRunning [get, set]
 Can be used to pause dispatching of incoming evtents (RPCs, Instantiates and anything else incoming). More...
 
static double Time [get]
 Photon network time, synched with the server. More...
 
static int ServerTimestamp [get]
 The current server's millisecond timestamp. More...
 
static float KeepAliveInBackground [get, set]
 Defines how many seconds PUN keeps the connection after Unity's OnApplicationPause(true) call. Default: 60 seconds. More...
 
static float BackgroundTimeout [get, set]
 
static bool IsMasterClient [get]
 Are we the master client? More...
 
static Player MasterClient [get]
 The Master Client of the current room or null (outside of rooms). More...
 
static bool InRoom [get]
 Is true while being in a room (NetworkClientState == ClientState.Joined). More...
 
static int CountOfPlayersOnMaster [get]
 The count of players currently looking for a room (available on MasterServer in 5sec intervals). More...
 
static int CountOfPlayersInRooms [get]
 Count of users currently playing your app in some room (sent every 5sec by Master Server). Use PhotonNetwork.PlayerList.Length or PhotonNetwork.CurrentRoom.PlayerCount to get the count of players in the room you're in! More...
 
static int CountOfPlayers [get]
 The count of players currently using this application (available on MasterServer in 5sec intervals). More...
 
static int CountOfRooms [get]
 The count of rooms currently in use (available on MasterServer in 5sec intervals). More...
 
static bool NetworkStatisticsEnabled [get, set]
 Enables or disables the collection of statistics about this client's traffic. More...
 
static int ResentReliableCommands [get]
 Count of commands that got repeated (due to local repeat-timing before an ACK was received). More...
 
static bool CrcCheckEnabled [get, set]
 Crc checks can be useful to detect and avoid issues with broken datagrams. Can be enabled while not connected. More...
 
static int PacketLossByCrcCheck [get]
 If CrcCheckEnabled, this counts the incoming packages that don't have a valid CRC checksum and got rejected. More...
 
static int MaxResendsBeforeDisconnect [get, set]
 Defines the number of times a reliable message can be resent before not getting an ACK for it will trigger a disconnect. Default: 5. More...
 
static int QuickResends [get, set]
 In case of network loss, reliable messages can be repeated quickly up to 3 times. More...
 
static bool UseAlternativeUdpPorts [get, set]
 Switch to alternative ports for a UDP connection to the Public Cloud. More...
 
static PhotonView[] PhotonViews [get]
 Gets the photon views. More...
 
static IPunPrefabPool PrefabPool [get, set]
 An Object Pool can be used to keep and reuse instantiated object instances. Replaces Unity's default Instantiate and Destroy methods. More...
 
static float LevelLoadingProgress [get]
 Represents the scene loading progress when using LoadLevel(). More...
 

Detailed Description

The main class to use the PhotonNetwork plugin. This class is static.

Member Function Documentation

static void AddCallbackTarget ( object  target)
static

Registers an object for callbacks for the implemented callback-interfaces.

The covered callback interfaces are: IConnectionCallbacks, IMatchmakingCallbacks, ILobbyCallbacks, IInRoomCallbacks, IOnEventCallback and IWebRpcCallback.

See: .Net Callbacks

Parameters
targetThe object that registers to get callbacks from PUN's LoadBalancingClient.
static bool AllocateSceneViewID ( PhotonView  view)
static

Enables the Master Client to allocate a viewID that is valid for scene objects.

Returns
static bool AllocateViewID ( PhotonView  view)
static

Allocates a viewID for the current/local player.

Returns
static bool CloseConnection ( Player  kickPlayer)
static

Request a client to disconnect (KICK). Only the master client can do this

Only the target player gets this event. That player will disconnect automatically, which is what the others will notice, too.

Parameters
kickPlayerThe Player to kick.
static bool ConnectToBestCloudServer ( )
static

Connect to the Photon Cloud region with the lowest ping (on platforms that support Unity's Ping).

Will save the result of pinging all cloud servers in PlayerPrefs. Calling this the first time can take +-2 seconds. The ping result can be overridden via PhotonNetwork.OverrideBestCloudServer(..) This call can take up to 2 seconds if it is the first time you are using this, all cloud servers will be pinged to check for the best region.

The PUN Setup Wizard stores your appID in a settings file and applies a server address/port. To connect to the Photon Cloud, a valid AppId must be in the settings file (shown in the Photon Cloud Dashboard). https://dashboard.photonengine.com

Connecting to the Photon Cloud might fail due to:

  • Invalid AppId
  • Network issues
  • Invalid region
  • Subscription CCU limit reached
  • etc.

In general check out the DisconnectCause from the IConnectionCallbacks.OnDisconnected callback.

Returns
If this client is going to connect to cloud server based on ping. Even if true, this does not guarantee a connection but the attempt is being made.
static bool ConnectToMaster ( string  masterServerAddress,
int  port,
string  appID 
)
static

Connect to a Photon Master Server by address, port, appID.

To connect to the Photon Cloud, a valid AppId must be in the settings file (shown in the Photon Cloud Dashboard). https://dashboard.photonengine.com

Connecting to the Photon Cloud might fail due to:

  • Invalid AppId
  • Network issues
  • Invalid region
  • Subscription CCU limit reached
  • etc.

In general check out the DisconnectCause from the IConnectionCallbacks.OnDisconnected callback.

Parameters
masterServerAddressThe server's address (either your own or Photon Cloud address).
portThe server's port to connect to.
appIDYour application ID (Photon Cloud provides you with a GUID for your game).
static bool ConnectToRegion ( string  region)
static

Connects to the Photon Cloud region of choice.

static bool ConnectUsingSettings ( )
static

Connect to Photon as configured in the PhotonServerSettings file.

Implement IConnectionCallbacks, to make your game logic aware of state changes. Especially, IConnectionCallbacks.ConnectedToMasterServer is useful to react when the client can do matchmaking.

This method will disable OfflineMode (which won't destroy any instantiated GOs) and it will set IsMessageQueueRunning to true.

Your Photon configuration is created by the PUN Wizard and contains the AppId, region for Photon Cloud games, the server address among other things.

To ignore the settings file, set the relevant values and connect by calling ConnectToMaster, ConnectToRegion.

To connect to the Photon Cloud, a valid AppId must be in the settings file (shown in the Photon Cloud Dashboard). https://dashboard.photonengine.com

Connecting to the Photon Cloud might fail due to:

  • Invalid AppId
  • Network issues
  • Invalid region
  • Subscription CCU limit reached
  • etc.

In general check out the DisconnectCause from the IConnectionCallbacks.OnDisconnected callback.

static bool CreateRoom ( string  roomName,
RoomOptions  roomOptions = null,
TypedLobby  typedLobby = null,
string[]  expectedUsers = null 
)
static

Creates a new room. Will callback: OnCreatedRoom and OnJoinedRoom or OnCreateRoomFailed.

When successful, this calls the callbacks OnCreatedRoom and OnJoinedRoom (the latter, cause you join as first player). In all error cases, OnCreateRoomFailed gets called.

Creating a room will fail if the room name is already in use or when the RoomOptions clashing with one another. Check the EnterRoomParams reference for the various room creation options.

If you don't want to create a unique room-name, pass null or "" as name and the server will assign a roomName (a GUID as string).

This method can only be called while the client is connected to a Master Server so you should implement the callback OnConnectedToMaster. Check the return value to make sure the operation will be called on the server. Note: There will be no callbacks if this method returned false.

More about PUN matchmaking: https://doc.photonengine.com/en-us/pun/v2/lobby-and-matchmaking/matchmaking-and-lobby

Parameters
roomNameUnique name of the room to create. Pass null or "" to make the server generate a name.
roomOptionsCommon options for the room like MaxPlayers, initial custom room properties and similar. See RoomOptions type..
typedLobbyIf null, the room is automatically created in the currently used lobby (which is "default" when you didn't join one explicitly).
expectedUsersOptional list of users (by UserId) who are expected to join this game and who you want to block a slot for.
Returns
If the operation got queued and will be sent.
static void Destroy ( PhotonView  targetView)
static

Network-Destroy the GameObject associated with the PhotonView, unless the PhotonView is static or not under this client's control.

Destroying a networked GameObject while in a Room includes:

  • Removal of the Instantiate call from the server's room buffer.
  • Removing RPCs buffered for PhotonViews that got created indirectly with the PhotonNetwork.Instantiate call.
  • Sending a message to other clients to remove the GameObject also (affected by network lag).

Usually, when you leave a room, the GOs get destroyed automatically. If you have to destroy a GO while not in a room, the Destroy is only done locally.

Destroying networked objects works only if they got created with PhotonNetwork.Instantiate(). Objects loaded with a scene are ignored, no matter if they have PhotonView components.

The GameObject must be under this client's control:

  • Instantiated and owned by this client.
  • Instantiated objects of players who left the room are controlled by the Master Client.
  • Scene-owned game objects are controlled by the Master Client.
  • GameObject can be destroyed while client is not in a room.
Returns
Nothing. Check error debug log for any issues.
static void Destroy ( GameObject  targetGo)
static

Network-Destroy the GameObject, unless it is static or not under this client's control.

Destroying a networked GameObject includes:

  • Removal of the Instantiate call from the server's room buffer.
  • Removing RPCs buffered for PhotonViews that got created indirectly with the PhotonNetwork.Instantiate call.
  • Sending a message to other clients to remove the GameObject also (affected by network lag).

Usually, when you leave a room, the GOs get destroyed automatically. If you have to destroy a GO while not in a room, the Destroy is only done locally.

Destroying networked objects works only if they got created with PhotonNetwork.Instantiate(). Objects loaded with a scene are ignored, no matter if they have PhotonView components.

The GameObject must be under this client's control:

  • Instantiated and owned by this client.
  • Instantiated objects of players who left the room are controlled by the Master Client.
  • Scene-owned game objects are controlled by the Master Client.
  • GameObject can be destroyed while client is not in a room.
Returns
Nothing. Check error debug log for any issues.
static void DestroyAll ( )
static

Network-Destroy all GameObjects, PhotonViews and their RPCs in the room. Removes anything buffered from the server. Can only be called by Master Client (for anyone).

Can only be called by Master Client (for anyone). Unlike the Destroy methods, this will remove anything from the server's room buffer. If your game buffers anything beyond Instantiate and RPC calls, that will be cleaned as well from server.

Destroying all includes:

  • Remove anything from the server's room buffer (Instantiate, RPCs, anything buffered).
  • Sending a message to other clients to destroy everything locally, too (affected by network lag).

Destroying networked objects works only if they got created with PhotonNetwork.Instantiate(). Objects loaded with a scene are ignored, no matter if they have PhotonView components.

Returns
Nothing. Check error debug log for any issues.
static void DestroyPlayerObjects ( int  playerId,
bool  localOnly 
)
static

Destroys all Instantiates and RPCs locally and (if not localOnly) sends EvDestroy(player) and clears related events in the server buffer.

static void DestroyPlayerObjects ( Player  targetPlayer)
static

Network-Destroy all GameObjects, PhotonViews and their RPCs of targetPlayer. Can only be called on local player (for "self") or Master Client (for anyone).

Destroying a networked GameObject includes:

  • Removal of the Instantiate call from the server's room buffer.
  • Removing RPCs buffered for PhotonViews that got created indirectly with the PhotonNetwork.Instantiate call.
  • Sending a message to other clients to remove the GameObject also (affected by network lag).

Destroying networked objects works only if they got created with PhotonNetwork.Instantiate(). Objects loaded with a scene are ignored, no matter if they have PhotonView components.

Returns
Nothing. Check error debug log for any issues.
static void DestroyPlayerObjects ( int  targetPlayerId)
static

Network-Destroy all GameObjects, PhotonViews and their RPCs of this player (by ID). Can only be called on local player (for "self") or Master Client (for anyone).

Destroying a networked GameObject includes:

  • Removal of the Instantiate call from the server's room buffer.
  • Removing RPCs buffered for PhotonViews that got created indirectly with the PhotonNetwork.Instantiate call.
  • Sending a message to other clients to remove the GameObject also (affected by network lag).

Destroying networked objects works only if they got created with PhotonNetwork.Instantiate(). Objects loaded with a scene are ignored, no matter if they have PhotonView components.

Returns
Nothing. Check error debug log for any issues.
static void Disconnect ( )
static

Makes this client disconnect from the photon server, a process that leaves any room and calls OnDisconnected on completion.

When you disconnect, the client will send a "disconnecting" message to the server. This speeds up leave/disconnect messages for players in the same room as you (otherwise the server would timeout this client's connection). When used in OfflineMode, the state-change and event-call OnDisconnected are immediate. Offline mode is set to false as well. Once disconnected, the client can connect again. Use ConnectUsingSettings.

static void FetchServerTimestamp ( )
static

Refreshes the server timestamp (async operation, takes a roundtrip).

Can be useful if a bad connection made the timestamp unusable or imprecise.

static bool FindFriends ( string[]  friendsToFind)
static

Requests the rooms and online status for a list of friends and saves the result in PhotonNetwork.Friends.

Works only on Master Server to find the rooms played by a selected list of users.

The result will be stored in PhotonNetwork.Friends when available. That list is initialized on first use of OpFindFriends (before that, it is null). To refresh the list, call FindFriends again (in 5 seconds or 10 or 20).

Users identify themselves by setting a unique userId in the PhotonNetwork.AuthValues. See remarks of AuthenticationValues for info about how this is set and used.

The list of friends must be fetched from some other source (not provided by Photon).

Internal: The server response includes 2 arrays of info (each index matching a friend from the request): ParameterCode.FindFriendsResponseOnlineList = bool[] of online states ParameterCode.FindFriendsResponseRoomIdList = string[] of room names (empty string if not in a room)

Parameters
friendsToFindArray of friend (make sure to use unique NickName or AuthValues).
Returns
If the operation could be sent (requires connection, only one request is allowed at any time). Always false in offline mode.
static HashSet<GameObject> FindGameObjectsWithComponent ( Type  type)
static

Finds the GameObjects with Components of a specific type (using FindObjectsOfType).

Parameters
typeType must be a Component
Returns
HashSet with GameObjects that have a specific type of Component.
static bool GetCustomRoomList ( TypedLobby  typedLobby,
string  sqlLobbyFilter 
)
static

Fetches a custom list of games from the server, matching a SQL-like "where" clause, then triggers OnRoomListUpdate callback.

Operation is only available for lobbies of type SqlLobby. This is an async request.

Note: You don't have to join a lobby to query it. Rooms need to be "attached" to a lobby, which can be done via the typedLobby parameter in CreateRoom, JoinOrCreateRoom, etc..

When done, OnRoomListUpdate gets called.

https://doc.photonengine.com/en-us/pun/v2/lobby-and-matchmaking/matchmaking-and-lobby/::sql_lobby_type

Parameters
typedLobbyThe lobby to query. Has to be of type SqlLobby.
sqlLobbyFilterThe sql query statement.
Returns
If the operation could be sent (has to be connected).
static int GetPing ( )
static

The current roundtrip time to the photon server.

Returns
Roundtrip time (to server and back).
static bool JoinLobby ( )
static

On MasterServer this joins the default lobby which list rooms currently in use.

The room list is sent and refreshed by the server using ILobbyCallbacks.OnRoomListUpdate.

Per room you should check if it's full or not before joining. Photon also lists rooms that are full, unless you close and hide them (room.open = false and room.visible = false).

In best case, you make your clients join random games, as described here: https://doc.photonengine.com/en-us/pun/v2/lobby-and-matchmaking/matchmaking-and-lobby

You can show your current players and room count without joining a lobby (but you must be on the master server). Use: CountOfPlayers, CountOfPlayersOnMaster, CountOfPlayersInRooms and CountOfRooms.

You can use more than one lobby to keep the room lists shorter. See JoinLobby(TypedLobby lobby). When creating new rooms, they will be "attached" to the currently used lobby or the default lobby.

You can use JoinRandomRoom without being in a lobby!

static bool JoinLobby ( TypedLobby  typedLobby)
static

On a Master Server you can join a lobby to get lists of available rooms.

The room list is sent and refreshed by the server using ILobbyCallbacks.OnRoomListUpdate.

Any client can "make up" any lobby on the fly. Splitting rooms into multiple lobbies will keep each list shorter. However, having too many lists might ruin the matchmaking experience.

In best case, you create a limited number of lobbies. For example, create a lobby per game-mode: "koth" for king of the hill and "ffa" for free for all, etc.

There is no listing of lobbies at the moment.

Sql-typed lobbies offer a different filtering model for random matchmaking. This might be more suited for skillbased-games. However, you will also need to follow the conventions for naming filterable properties in sql-lobbies! Both is explained in the matchmaking doc linked below.

In best case, you make your clients join random games, as described here: https://doc.photonengine.com/en-us/realtime/current/reference/matchmaking-and-lobby

Per room you should check if it's full or not before joining. Photon does list rooms that are full, unless you close and hide them (room.open = false and room.visible = false).

You can show your games current players and room count without joining a lobby (but you must be on the master server). Use: CountOfPlayers, CountOfPlayersOnMaster, CountOfPlayersInRooms and CountOfRooms.

When creating new rooms, they will be "attached" to the currently used lobby or the default lobby.

You can use JoinRandomRoom without being in a lobby!

Parameters
typedLobbyA typed lobby to join (must have name and type).
static bool JoinOrCreateRoom ( string  roomName,
RoomOptions  roomOptions,
TypedLobby  typedLobby,
string[]  expectedUsers = null 
)
static

Joins a specific room by name and creates it on demand. Will callback: OnJoinedRoom or OnJoinRoomFailed.

Useful when players make up a room name to meet in: All involved clients call the same method and whoever is first, also creates the room.

When successful, the client will enter the specified room. The client which creates the room, will callback both OnCreatedRoom and OnJoinedRoom. Clients that join an existing room will only callback OnJoinedRoom. In all error cases, OnJoinRoomFailed gets called.

Joining a room will fail, if the room is full, closed or when the user already is present in the room (checked by userId).

To return to a room, use OpRejoinRoom.

This method can only be called while the client is connected to a Master Server so you should implement the callback OnConnectedToMaster. Check the return value to make sure the operation will be called on the server. Note: There will be no callbacks if this method returned false.

If you set room properties in roomOptions, they get ignored when the room is existing already. This avoids changing the room properties by late joining players.

You can define an array of expectedUsers, to block player slots in the room for these users. The corresponding feature in Photon is called "Slot Reservation" and can be found in the doc pages.

More about PUN matchmaking: https://doc.photonengine.com/en-us/pun/v2/lobby-and-matchmaking/matchmaking-and-lobby

Parameters
roomNameName of the room to join. Must be non null.
roomOptionsOptions for the room, in case it does not exist yet. Else these values are ignored.
typedLobbyLobby you want a new room to be listed in. Ignored if the room was existing and got joined.
expectedUsersOptional list of users (by UserId) who are expected to join this game and who you want to block a slot for.
Returns
If the operation got queued and will be sent.
static bool JoinRandomRoom ( )
static

Joins a random room that matches the filter. Will callback: OnJoinedRoom or OnJoinRandomFailed.

Used for random matchmaking. You can join any room or one with specific properties defined in opJoinRandomRoomParams.

This operation fails if no rooms are fitting or available (all full, closed, in another lobby or not visible). It may also fail when actually joining the room which was found. Rooms may close, become full or empty anytime.

This method can only be called while the client is connected to a Master Server so you should implement the callback OnConnectedToMaster. Check the return value to make sure the operation will be called on the server. Note: There will be no callbacks if this method returned false.

More about PUN matchmaking: https://doc.photonengine.com/en-us/pun/v2/lobby-and-matchmaking/matchmaking-and-lobby

static bool JoinRandomRoom ( Hashtable  expectedCustomRoomProperties,
byte  expectedMaxPlayers 
)
static

Joins a random room that matches the filter. Will callback: OnJoinedRoom or OnJoinRandomFailed.

Used for random matchmaking. You can join any room or one with specific properties defined in opJoinRandomRoomParams.

This operation fails if no rooms are fitting or available (all full, closed, in another lobby or not visible). It may also fail when actually joining the room which was found. Rooms may close, become full or empty anytime.

This method can only be called while the client is connected to a Master Server so you should implement the callback OnConnectedToMaster. Check the return value to make sure the operation will be called on the server. Note: There will be no callbacks if this method returned false.

More about PUN matchmaking: https://doc.photonengine.com/en-us/pun/v2/lobby-and-matchmaking/matchmaking-and-lobby

Parameters
expectedCustomRoomPropertiesFilters for rooms that match these custom properties (string keys and values). To ignore, pass null.
expectedMaxPlayersFilters for a particular maxplayer setting. Use 0 to accept any maxPlayer value.
Returns
If the operation got queued and will be sent.
static bool JoinRandomRoom ( Hashtable  expectedCustomRoomProperties,
byte  expectedMaxPlayers,
MatchmakingMode  matchingType,
TypedLobby  typedLobby,
string  sqlLobbyFilter,
string[]  expectedUsers = null 
)
static

Joins a random room that matches the filter. Will callback: OnJoinedRoom or OnJoinRandomFailed.

Used for random matchmaking. You can join any room or one with specific properties defined in opJoinRandomRoomParams.

This operation fails if no rooms are fitting or available (all full, closed, in another lobby or not visible). It may also fail when actually joining the room which was found. Rooms may close, become full or empty anytime.

This method can only be called while the client is connected to a Master Server so you should implement the callback OnConnectedToMaster. Check the return value to make sure the operation will be called on the server. Note: There will be no callbacks if this method returned false.

More about PUN matchmaking: https://doc.photonengine.com/en-us/pun/v2/lobby-and-matchmaking/matchmaking-and-lobby

Parameters
expectedCustomRoomPropertiesFilters for rooms that match these custom properties (string keys and values). To ignore, pass null.
expectedMaxPlayersFilters for a particular maxplayer setting. Use 0 to accept any maxPlayer value.
matchingTypeSelects one of the available matchmaking algorithms. See MatchmakingMode enum for options.
typedLobbyThe lobby in which you want to lookup a room. Pass null, to use the default lobby. This does not join that lobby and neither sets the lobby property.
sqlLobbyFilterA filter-string for SQL-typed lobbies.
expectedUsersOptional list of users (by UserId) who are expected to join this game and who you want to block a slot for.
Returns
If the operation got queued and will be sent.
static bool JoinRoom ( string  roomName,
string[]  expectedUsers = null 
)
static

Joins a room by name. Will callback: OnJoinedRoom or OnJoinRoomFailed.

Useful when using lobbies or when players follow friends or invite each other.

When successful, the client will enter the specified room and callback via OnJoinedRoom. In all error cases, OnJoinRoomFailed gets called.

Joining a room will fail if the room is full, closed, not existing or when the user already is present in the room (checked by userId).

To return to a room, use OpRejoinRoom. When players invite each other and it's unclear who's first to respond, use OpJoinOrCreateRoom instead.

This method can only be called while the client is connected to a Master Server so you should implement the callback OnConnectedToMaster. Check the return value to make sure the operation will be called on the server. Note: There will be no callbacks if this method returned false.

More about PUN matchmaking: https://doc.photonengine.com/en-us/pun/v2/lobby-and-matchmaking/matchmaking-and-lobby

OnJoinRoomFailed OnJoinedRoom

Parameters
roomNameUnique name of the room to join.
expectedUsersOptional list of users (by UserId) who are expected to join this game and who you want to block a slot for.
Returns
If the operation got queued and will be sent.
static bool LeaveLobby ( )
static

Leave a lobby to stop getting updates about available rooms.

This does not reset PhotonNetwork.lobby! This allows you to join this particular lobby later easily.

The values CountOfPlayers, CountOfPlayersOnMaster, CountOfPlayersInRooms and CountOfRooms are received even without being in a lobby.

You can use JoinRandomRoom without being in a lobby.

static bool LeaveRoom ( bool  becomeInactive = true)
static

Leave the current room and return to the Master Server where you can join or create rooms (see remarks).

This will clean up all (network) GameObjects with a PhotonView, unless you changed autoCleanUp to false. Returns to the Master Server.

In OfflineMode, the local "fake" room gets cleaned up and OnLeftRoom gets called immediately.

In a room with playerTTL < 0, LeaveRoom just turns a client inactive. The player stays in the room's player list and can return later on. Setting becomeInactive to false deliberately, means to "abandon" the room, despite the playerTTL allowing you to come back.

In a room with playerTTL == 0, become inactive has no effect (clients are removed from the room right away).

Parameters
becomeInactiveIf this client becomes inactive in a room with playerTTL < 0. Defaults to true.
static void LoadLevel ( int  levelNumber)
static

This method wraps loading a level asynchronously and pausing network messages during the process.

While loading levels in a networked game, it makes sense to not dispatch messages received by other players. LoadLevel takes care of that by setting PhotonNetwork.IsMessageQueueRunning = false until the scene loaded.

To sync the loaded level in a room, set PhotonNetwork.AutomaticallySyncScene to true. The Master Client of a room will then sync the loaded level with every other player in the room. Note that this works only for a single active scene and that reloading the scene is not supported. The Master Client will actually reload a scene but other clients won't.

You should make sure you don't fire RPCs before you load another scene (which doesn't contain the same GameObjects and PhotonViews).

LoadLevel uses SceneManager.LoadSceneAsync().

Check the progress of the LevelLoading using PhotonNetwork.LevelLoadingProgress.

Calling LoadLevel before the previous scene finished loading is not recommended. If AutomaticallySyncScene is enabled, PUN cancels the previous load (and prevent that from becoming the active scene). If AutomaticallySyncScene is off, the previous scene loading can finish. In both cases, a new scene is loaded locally.

Parameters
levelNumberBuild-index number of the level to load. When using level numbers, make sure they are identical on all clients.
static void LoadLevel ( string  levelName)
static

This method wraps loading a level asynchronously and pausing network messages during the process.

While loading levels in a networked game, it makes sense to not dispatch messages received by other players. LoadLevel takes care of that by setting PhotonNetwork.IsMessageQueueRunning = false until the scene loaded.

To sync the loaded level in a room, set PhotonNetwork.AutomaticallySyncScene to true. The Master Client of a room will then sync the loaded level with every other player in the room. Note that this works only for a single active scene and that reloading the scene is not supported. The Master Client will actually reload a scene but other clients won't.

You should make sure you don't fire RPCs before you load another scene (which doesn't contain the same GameObjects and PhotonViews).

LoadLevel uses SceneManager.LoadSceneAsync().

Check the progress of the LevelLoading using PhotonNetwork.LevelLoadingProgress.

Calling LoadLevel before the previous scene finished loading is not recommended. If AutomaticallySyncScene is enabled, PUN cancels the previous load (and prevent that from becoming the active scene). If AutomaticallySyncScene is off, the previous scene loading can finish. In both cases, a new scene is loaded locally.

Parameters
levelNameName of the level to load. Make sure it's available to all clients in the same room.
static void NetworkStatisticsReset ( )
static

Resets the traffic stats and re-enables them.

static string NetworkStatisticsToString ( )
static

Only available when NetworkStatisticsEnabled was used to gather some stats.

Returns
A string with vital networking statistics.
static void OpCleanActorRpcBuffer ( int  actorNumber)
static

Removes the RPCs of someone else (to be used as master). This won't clean any local caches. It just tells the server to forget a player's RPCs and instantiates.

Parameters
actorNumber
static void OpCleanRpcBuffer ( PhotonView  view)
static

Cleans server RPCs for PhotonView (without any further checks).

static void OpRemoveCompleteCacheOfPlayer ( int  actorNumber)
static

Instead removing RPCs or Instantiates, this removed everything cached by the actor.

Parameters
actorNumber
static bool RaiseEvent ( byte  eventCode,
object  eventContent,
RaiseEventOptions  raiseEventOptions,
SendOptions  sendOptions 
)
static

Sends fully customizable events in a room. Events consist of at least an EventCode (0..199) and can have content.

To receive events, implement IOnEventCallback in any class and register it via PhotonNetwork.AddCallbackTarget. See IOnEventCallback.OnEvent.

The eventContent is optional. If set, eventContent must be a "serializable type", something that the client can turn into a byte[] basically. Most basic types and arrays of them are supported, including Unity's Vector2, Vector3, Quaternion. Transforms are not supported.

You can turn a class into a "serializable type" by following the example in CustomTypes.cs.

The RaiseEventOptions have some (less intuitive) combination rules: If you set targetActors (an array of Player.ID values), the receivers parameter gets ignored. When using event caching, the targetActors, receivers and interestGroup can't be used. Buffered events go to all. When using cachingOption removeFromRoomCache, the eventCode and content are actually not sent but used as filter.

Parameters
eventCodeA byte identifying the type of event. You might want to use a code per action or to signal which content can be expected. Allowed: 0..199.
eventContentSome serializable object like string, byte, integer, float (etc) and arrays of those. Hashtables with byte keys are good to send variable content.
raiseEventOptionsAllows more complex usage of events. If null, RaiseEventOptions.Default will be used (which is fine).
sendOptionsSend options for reliable, encryption etc..
Returns
False if event could not be sent.
static bool Reconnect ( )
static

Can be used to reconnect to the master server after a disconnect.

After losing connection, you can use this to connect a client to the region Master Server again. Cache the room name you're in and use RejoinRoom(roomname) to return to a game. Common use case: Press the Lock Button on a iOS device and you get disconnected immediately.

static bool ReconnectAndRejoin ( )
static

When the client lost connection during gameplay, this method attempts to reconnect and rejoin the room.

This method re-connects directly to the game server which was hosting the room PUN was in before. If the room was shut down in the meantime, PUN will call OnJoinRoomFailed and return this client to the Master Server.

Check the return value, if this client will attempt a reconnect and rejoin (if the conditions are met). If ReconnectAndRejoin returns false, you can still attempt a Reconnect and Rejoin.

Similar to PhotonNetwork.RejoinRoom, this requires you to use unique IDs per player (the UserID).

Rejoining room will not send any player properties. Instead client will receive up-to-date ones from server. If you want to set new player properties, do it once rejoined.

Returns
False, if there is no known room or game server to return to. Then, this client does not attempt the ReconnectAndRejoin.
static bool RejoinRoom ( string  roomName)
static

Rejoins a room by roomName (using the userID internally to return). Will callback: OnJoinedRoom or OnJoinRoomFailed.

After losing connection, you might be able to return to a room and continue playing, if the client is reconnecting fast enough. Use Reconnect() and this method. Cache the room name you're in and use RejoinRoom(roomname) to return to a game.

Note: To be able to Rejoin any room, you need to use UserIDs! You also need to set RoomOptions.PlayerTtl.

Important: Instantiate() and use of RPCs is not yet supported. The ownership rules of PhotonViews prevent a seamless return to a game, if you use PhotonViews. Use Custom Properties and RaiseEvent with event caching instead.

Common use case: Press the Lock Button on a iOS device and you get disconnected immediately.

Rejoining room will not send any player properties. Instead client will receive up-to-date ones from server. If you want to set new player properties, do it once rejoined.

static void RemoveCallbackTarget ( object  target)
static

Removes the target object from callbacks for its implemented callback-interfaces.

The covered callback interfaces are: IConnectionCallbacks, IMatchmakingCallbacks, ILobbyCallbacks, IInRoomCallbacks, IOnEventCallback and IWebRpcCallback.

See: .Net Callbacks

Parameters
targetThe object that unregisters from getting callbacks.
static void RemovePlayerCustomProperties ( string[]  customPropertiesToDelete)
static

Locally removes Custom Properties of "this" player. Important: This does not synchronize the change! Useful when you switch rooms.

Use this method with care. It can create inconsistencies of state between players! This only changes the player.customProperties locally. This can be useful to clear your Custom Properties between games (let's say they store which turn you made, kills, etc).

SetPlayerCustomProperties() syncs and can be used to set values to null while in a room. That can be considered "removed" while in a room.

If customPropertiesToDelete is null or has 0 entries, all Custom Properties are deleted (replaced with a new Hashtable). If you specify keys to remove, those will be removed from the Hashtable but other keys are unaffected.

Parameters
customPropertiesToDeleteList of Custom Property keys to remove. See remarks.
static void RemoveRPCs ( Player  targetPlayer)
static

Remove all buffered RPCs from server that were sent by targetPlayer. Can only be called on local player (for "self") or Master Client (for anyone).

This method requires either:

  • This is the targetPlayer's client.
  • This client is the Master Client (can remove any Player's RPCs).

If the targetPlayer calls RPCs at the same time that this is called, network lag will determine if those get buffered or cleared like the rest.

Parameters
targetPlayerThis player's buffered RPCs get removed from server buffer.
static void RemoveRPCs ( PhotonView  targetPhotonView)
static

Remove all buffered RPCs from server that were sent via targetPhotonView. The Master Client and the owner of the targetPhotonView may call this.

This method requires either:

  • The targetPhotonView is owned by this client (Instantiated by it).
  • This client is the Master Client (can remove any PhotonView's RPCs).
Parameters
targetPhotonViewRPCs buffered for this PhotonView get removed from server buffer.
static void RemoveRPCsInGroup ( int  group)
static

Remove all buffered RPCs from server that were sent in the targetGroup, if this is the Master Client or if this controls the individual PhotonView.

This method requires either:

  • This client is the Master Client (can remove any RPCs per group).
  • Any other client: each PhotonView is checked if it is under this client's control. Only those RPCs are removed.
Parameters
groupInterest group that gets all RPCs removed.
static void SendAllOutgoingCommands ( )
static

Can be used to immediately send the RPCs and Instantiates just called, so they are on their way to the other players.

This could be useful if you do a RPC to load a level and then load it yourself. While loading, no RPCs are sent to others, so this would delay the "load" RPC. You can send the RPC to "others", use this method, disable the message queue (by IsMessageQueueRunning) and then load.

static void SetInterestGroups ( byte[]  disableGroups,
byte[]  enableGroups 
)
static

Enable/disable receiving on given Interest Groups (applied to PhotonViews).

A client can tell the server which Interest Groups it's interested in. The server will only forward events for those Interest Groups to that client (saving bandwidth and performance).

See: https://doc.photonengine.com/en-us/pun/v2/gameplay/interestgroups

See: https://doc.photonengine.com/en-us/pun/v2/demos-and-tutorials/package-demos/culling-demo

Parameters
disableGroupsThe interest groups to disable (or null).
enableGroupsThe interest groups to enable (or null).
static void SetInterestGroups ( byte  group,
bool  enabled 
)
static

Enable/disable receiving events from a given Interest Group.

A client can tell the server which Interest Groups it's interested in. The server will only forward events for those Interest Groups to that client (saving bandwidth and performance).

See: https://doc.photonengine.com/en-us/pun/v2/gameplay/interestgroups

See: https://doc.photonengine.com/en-us/pun/v2/demos-and-tutorials/package-demos/culling-demo

Parameters
groupThe interest group to affect.
enabledSets if receiving from group to enabled (or not).
static void SetLevelPrefix ( byte  prefix)
static

Sets level prefix for PhotonViews instantiated later on. Don't set it if you need only one!

Important: If you don't use multiple level prefixes, simply don't set this value. The default value is optimized out of the traffic.

This won't affect existing PhotonViews (they can't be changed yet for existing PhotonViews).

Messages sent with a different level prefix will be received but not executed. This affects RPCs, Instantiates and synchronization.

Be aware that PUN never resets this value, you'll have to do so yourself.

Parameters
prefixMax value is short.MaxValue = 255
static bool SetMasterClient ( Player  masterClientPlayer)
static

Asks the server to assign another player as Master Client of your current room.

RPCs and RaiseEvent have the option to send messages only to the Master Client of a room. SetMasterClient affects which client gets those messages.

This method calls an operation on the server to set a new Master Client, which takes a roundtrip. In case of success, this client and the others get the new Master Client from the server.

SetMasterClient tells the server which current Master Client should be replaced with the new one. It will fail, if anything switches the Master Client moments earlier. There is no callback for this error. All clients should get the new Master Client assigned by the server anyways.

See also: PhotonNetwork.MasterClient

On v3 servers: The ReceiverGroup.MasterClient (usable in RPCs) is not affected by this (still points to lowest player.ID in room). Avoid using this enum value (and send to a specific player instead).

If the current Master Client leaves, PUN will detect a new one by "lowest player ID". Implement OnMasterClientSwitched to get a callback in this case. The PUN-selected Master Client might assign a new one.

Make sure you don't create an endless loop of Master-assigning! When selecting a custom Master Client, all clients should point to the same player, no matter who actually assigns this player.

Locally the Master Client is immediately switched, while remote clients get an event. This means the game is tempoarily without Master Client like when a current Master Client leaves.

When switching the Master Client manually, keep in mind that this user might leave and not do it's work, just like any Master Client.

Parameters
masterClientPlayerThe player to become the next Master Client.
Returns
False when this operation couldn't be done. Must be in a room (not in OfflineMode).
static void SetPlayerCustomProperties ( Hashtable  customProperties)
static

Sets this (local) player's properties and synchronizes them to the other players (don't modify them directly).

While in a room, your properties are synced with the other players. CreateRoom, JoinRoom and JoinRandomRoom will all apply your player's custom properties when you enter the room. The whole Hashtable will get sent. Minimize the traffic by setting only updated key/values.

If the Hashtable is null, the custom properties will be cleared. Custom properties are never cleared automatically, so they carry over to the next room, if you don't change them.

Don't set properties by modifying PhotonNetwork.player.customProperties!

Parameters
customPropertiesOnly string-typed keys will be used from this hashtable. If null, custom properties are all deleted.
static void SetSendingEnabled ( byte  group,
bool  enabled 
)
static

Enable/disable sending on given group (applied to PhotonViews)

This does not interact with the Photon server-side. It's just a client-side setting to suppress updates, should they be sent to one of the blocked groups.

This setting is not particularly useful, as it means that updates literally never reach the server or anyone else. Use with care.

Parameters
groupThe interest group to affect.
enabledSets if sending to group is enabled (or not).
static void SetSendingEnabled ( byte[]  disableGroups,
byte[]  enableGroups 
)
static

Enable/disable sending on given groups (applied to PhotonViews)

This does not interact with the Photon server-side. It's just a client-side setting to suppress updates, should they be sent to one of the blocked groups.

This setting is not particularly useful, as it means that updates literally never reach the server or anyone else. Use with care.

Parameters
enableGroupsThe interest groups to enable sending on (or null).
disableGroupsThe interest groups to disable sending on (or null).
static bool WebRpc ( string  name,
object  parameters,
bool  sendAuthCookie = false 
)
static

This operation makes Photon call your custom web-service by name (path) with the given parameters.

This is a server-side feature which must be setup in the Photon Cloud Dashboard prior to use. https://doc.photonengine.com/en-us/pun/v2/gameplay/web-extensions/webrpc The Parameters will be converted into JSon format, so make sure your parameters are compatible.

See Photon.Realtime.IWebRpcCallback.OnWebRpcResponse on how to get a response.

It's important to understand that the OperationResponse only tells if the WebRPC could be called. The content of the response contains any values your web-service sent and the error/success code. In case the web-service failed, an error code and a debug message are usually inside the OperationResponse.

The class WebRpcResponse is a helper-class that extracts the most valuable content from the WebRPC response.

Example callback implementation:

public void OnWebRpcResponse(OperationResponse response)
{
    WebRpcResponse webResponse = new WebRpcResponse(operationResponse);
    if (webResponse.ReturnCode != 0) { //...
    }
    switch (webResponse.Name) { //...
    }
    // and so on
}

Member Data Documentation

ConnectMethod ConnectMethod = ConnectMethod.NotCalled
static

Tracks, which Connect method was called last.

ConnectToMaster sets this to ConnectToMaster. ConnectToRegion sets this to ConnectToRegion. ConnectToBestCloudServer sets this to ConnectToBest. PhotonNetwork.ConnectUsingSettings will call either ConnectToMaster, ConnectToRegion or ConnectToBest, depending on the settings.

Controls how verbose PUN is.

readonly int MAX_VIEW_IDS = 1000
static

The maximum number of assigned PhotonViews per player (or scene). See the General Documentation topic "Limitations" on how to raise this limitation.

LoadBalancingClient NetworkingClient
static

The LoadBalancingClient is part of Photon Realtime and wraps up multiple servers and states for PUN.

int ObjectsInOneUpdate = 10
static

Defines how many OnPhotonSerialize()-calls might get summarized in one message.

A low number increases overhead, a high number might mean fragmentation.

ServerSettings PhotonServerSettings = (ServerSettings)Resources.Load(PhotonNetwork.ServerSettingsFileName, typeof(ServerSettings))
static

Serialized server settings, written by the Setup Wizard for use in ConnectUsingSettings.

float PrecisionForFloatSynchronization = 0.01f
static

The minimum difference between floats before we send it via a PhotonView's OnSerialize/ObservingComponent.

float PrecisionForQuaternionSynchronization = 1.0f
static

The minimum angle that a rotation needs to change before we send it via a PhotonView's OnSerialize/ObservingComponent.

float PrecisionForVectorSynchronization = 0.000099f
static

The minimum difference that a Vector2 or Vector3(e.g. a transforms rotation) needs to change before we send it via a PhotonView's OnSerialize/ObservingComponent.

Note that this is the sqrMagnitude. E.g. to send only after a 0.01 change on the Y-axix, we use 0.01f*0.01f=0.0001f. As a remedy against float inaccuracy we use 0.000099f instead of 0.0001f.

const string PunVersion = "2.12"

Version number of PUN. Used in the AppVersion, which separates your playerbase in matchmaking.

bool UseRpcMonoBehaviourCache
static

While enabled, the MonoBehaviours on which we call RPCs are cached, avoiding costly GetComponents<MonoBehaviour>() calls.

RPCs are called on the MonoBehaviours of a target PhotonView. Those have to be found via GetComponents.

When set this to true, the list of MonoBehaviours gets cached in each PhotonView. You can use photonView.RefreshRpcMonoBehaviourCache() to manually refresh a PhotonView's list of MonoBehaviours on demand (when a new MonoBehaviour gets added to a networked GameObject, e.g.).

Property Documentation

string AppVersion
staticget

Sent to Photon Server to specifiy the "Virtual AppId".

Sent with the operation Authenticate. When using PUN, you should set the GameVersion or use ConnectUsingSettings().

AuthenticationValues AuthValues
staticgetset

A user's authentication values used during connect.

Set these before calling Connect if you want custom authentication. These values set the userId, if and how that userId gets verified (server-side), etc..

If authentication fails for any values, PUN will call your implementation of OnCustomAuthenticationFailed(string debugMessage). See Photon.Realtime.IConnectionCallbacks.OnCustomAuthenticationFailed.

bool AutomaticallySyncScene
staticgetset

Defines if all clients in a room should automatically load the same level as the Master Client.

When enabled, clients load the same scene that is active on the Master Client. When a client joins a room, the scene gets loaded even before the callback OnJoinedRoom gets called.

To synchronize the loaded level, the Master Client should use PhotonNetwork.LoadLevel, which notifies the other clients before starting to load the scene. If the Master Client loads a level directly via Unity's API, PUN will notify the other players after the scene loading completed (using SceneManager.sceneLoaded).

Internally, a Custom Room Property is set for the loaded scene. On change, clients use LoadLevel if they are not in the same scene.

Note that this works only for a single active scene and that reloading the scene is not supported. The Master Client will actually reload a scene but other clients won't. To get everyone to reload, the game can send an RPC or event to trigger the loading.

string BestRegionSummaryInPreferences
staticgetset

Used to store and access the "Best Region Summary" in the Player Preferences.

string CloudRegion
staticget

Currently used Cloud Region (if any). As long as the client is not on a Master Server or Game Server, the region is not yet defined.

int CountOfPlayers
staticget

The count of players currently using this application (available on MasterServer in 5sec intervals).

int CountOfPlayersInRooms
staticget

Count of users currently playing your app in some room (sent every 5sec by Master Server). Use PhotonNetwork.PlayerList.Length or PhotonNetwork.CurrentRoom.PlayerCount to get the count of players in the room you're in!

int CountOfPlayersOnMaster
staticget

The count of players currently looking for a room (available on MasterServer in 5sec intervals).

int CountOfRooms
staticget

The count of rooms currently in use (available on MasterServer in 5sec intervals).

bool CrcCheckEnabled
staticgetset

Crc checks can be useful to detect and avoid issues with broken datagrams. Can be enabled while not connected.

TypedLobby CurrentLobby
staticget

The lobby that will be used when PUN joins a lobby or creates a game. This is defined when joining a lobby or creating rooms

The default lobby uses an empty string as name. So when you connect or leave a room, PUN automatically gets you into a lobby again.

Check PhotonNetwork.InLobby if the client is in a lobby. (masterServerAndLobby)

Room CurrentRoom
staticget

Get the room we're currently in (also when in OfflineMode). Null if we aren't in any room.

LoadBalancing Client is not aware of the Photon Offline Mode, so never use PhotonNetwork.NetworkingClient.CurrentRoom will be null if you are using OffLine Mode, while PhotonNetwork.CurrentRoom will be set when offlineMode is true

bool EnableLobbyStatistics
staticget

If enabled, the client will get a list of available lobbies from the Master Server.

Set this value before the client connects to the Master Server. While connected to the Master Server, a change has no effect.

Implement OptionalInfoCallbacks.OnLobbyStatisticsUpdate, to get the list of used lobbies.

The lobby statistics can be useful if your title dynamically uses lobbies, depending (e.g.) on current player activity or such. In this case, getting a list of available lobbies, their room-count and player-count can be useful info.

ConnectUsingSettings sets this to the PhotonServerSettings value.

string GameVersion
staticgetset

Version number of your game. Setting this updates the AppVersion, which separates your playerbase in matchmaking.

In PUN, the GameVersion is only one component of the LoadBalancingClient.AppVersion. Setting the GameVersion will also set the LoadBalancingClient.AppVersion to: value+'_'+ PhotonNetwork.PunVersion.

The AppVersion is used to split your playerbase as needed. One AppId may have various AppVersions and each is a separate set of users for matchmaking.

The AppVersion gets sent in the "Authenticate" step. This means you can set the GameVersion right after calling ConnectUsingSettings (e.g.) and the new value will be used on the server. Once the client is connected, authentication is done and the value won't be sent to the server anymore.

bool InLobby
staticget

True while this client is in a lobby.

Implement IPunCallbacks.OnRoomListUpdate() for a notification when the list of rooms becomes available or updated.

You are automatically leaving any lobby when you join a room! Lobbies only exist on the Master Server (whereas rooms are handled by Game Servers).

bool InRoom
staticget

Is true while being in a room (NetworkClientState == ClientState.Joined).

Aside from polling this value, game logic should implement IMatchmakingCallbacks in some class and react when that gets called.

Many actions can only be executed in a room, like Instantiate or Leave, etc.
A client can join a room in offline mode. In that case, don't use LoadBalancingClient.InRoom, which does not cover offline mode.

bool IsConnected
staticget

False until you connected to Photon initially. True in offline mode, while connected to any server and even while switching servers.

bool IsConnectedAndReady
staticget

A refined version of connected which is true only if your connection to the server is ready to accept operations like join, leave, etc.

bool IsMasterClient
staticget

Are we the master client?

bool IsMessageQueueRunning
staticgetset

Can be used to pause dispatching of incoming evtents (RPCs, Instantiates and anything else incoming).

While IsMessageQueueRunning == false, the OnPhotonSerializeView calls are not done and nothing is sent by a client. Also, incoming messages will be queued until you re-activate the message queue.

This can be useful if you first want to load a level, then go on receiving data of PhotonViews and RPCs. The client will go on receiving and sending acknowledgements for incoming packages and your RPCs/Events. This adds "lag" and can cause issues when the pause is longer, as all incoming messages are just queued.

float KeepAliveInBackground
staticgetset

Defines how many seconds PUN keeps the connection after Unity's OnApplicationPause(true) call. Default: 60 seconds.

It's best practice to disconnect inactive apps/connections after a while but to also allow users to take calls, etc.. We think a reasonable background timeout is 60 seconds.

To handle the timeout, implement: OnDisconnected(), as usual. Your application will "notice" the background disconnect when it becomes active again (running the Update() loop).

If you need to separate this case from others, you need to track if the app was in the background (there is no special callback by PUN).

Info: PUN is running a "fallback thread" to send ACKs to the server, even when Unity is not calling Update() regularly. This helps keeping the connection while loading scenes and assets and when the app is in the background.

Note: Some platforms (e.g. iOS) don't allow to keep a connection while the app is in background. In those cases, this value does not change anything, the app immediately loses connection in background.

Unity's OnApplicationPause() callback is broken in some exports (Android) of some Unity versions. Make sure OnApplicationPause() gets the callbacks you expect on the platform you target! Check PhotonHandler.OnApplicationPause(bool pause) to see the implementation.

float LevelLoadingProgress
staticget

Represents the scene loading progress when using LoadLevel().

The value is 0 if the app never loaded a scene with LoadLevel(). During async scene loading, the value is between 0 and 1. Once any scene completed loading, it stays at 1 (signaling "done").

The level loading progress. Ranges from 0 to 1.

Player LocalPlayer
staticget

This client's Player instance is always available, unless the app shuts down.

Useful (e.g.) to set the Custom Player Properties or the NickName for this client anytime. When the client joins a room, the Custom Properties and other values are synced.

Player MasterClient
staticget

The Master Client of the current room or null (outside of rooms).

Can be used as "authoritative" client/player to make descisions, run AI or other.

If the current Master Client leaves the room (leave/disconnect), the server will quickly assign someone else. If the current Master Client times out (closed app, lost connection, etc), messages sent to this client are effectively lost for the others! A timeout can take 10 seconds in which no Master Client is active.

Implement the method IPunCallbacks.OnMasterClientSwitched to be called when the Master Client switched.

Use PhotonNetwork.SetMasterClient, to switch manually to some other player / client.

With OfflineMode == true, this always returns the PhotonNetwork.player.

int MaxResendsBeforeDisconnect
staticgetset

Defines the number of times a reliable message can be resent before not getting an ACK for it will trigger a disconnect. Default: 5.

Less resends mean quicker disconnects, while more can lead to much more lag without helping. Min: 3. Max: 10.

ClientState NetworkClientState
staticget

Directly provides the network-level client state, unless in OfflineMode.

In context of PUN, you should usually use IsConnected or IsConnectedAndReady.

This is the lower level connection state. Keep in mind that PUN uses more than one server, so the client may become Disconnected, even though it's just switching servers.

While OfflineMode is true, this is ClientState.Joined (after create/join) or ConnectedToMasterServer in all other cases.

bool NetworkStatisticsEnabled
staticgetset

Enables or disables the collection of statistics about this client's traffic.

If you encounter issues with clients, the traffic stats are a good starting point to find solutions. Only with enabled stats, you can use GetVitalStats

string NickName
staticgetset

Set to synchronize the player's nickname with everyone in the room(s) you enter. This sets PhotonNetwork.player.NickName.

The NickName is just a nickname and does not have to be unique or backed up with some account.
Set the value any time (e.g. before you connect) and it will be available to everyone you play with.
Access the names of players by: Player.NickName.
PhotonNetwork.PlayerListOthers is a list of other players - each contains the NickName the remote player set.

bool OfflineMode
staticgetset

Offline mode can be set to re-use your multiplayer code in singleplayer game modes. When this is on PhotonNetwork will not create any connections and there is near to no overhead. Mostly usefull for reusing RPC's and PhotonNetwork.Instantiate

int PacketLossByCrcCheck
staticget

If CrcCheckEnabled, this counts the incoming packages that don't have a valid CRC checksum and got rejected.

PhotonView [] PhotonViews
staticget

Gets the photon views.

This is an expensive operation as it returns a copy of the internal list.

The photon views.

Player [] PlayerList
staticget

A sorted copy of the players-list of the current room. This is using Linq, so better cache this value. Update when players join / leave.

Player [] PlayerListOthers
staticget

A sorted copy of the players-list of the current room, excluding this client. This is using Linq, so better cache this value. Update when players join / leave.

IPunPrefabPool PrefabPool
staticgetset

An Object Pool can be used to keep and reuse instantiated object instances. Replaces Unity's default Instantiate and Destroy methods.

Defaults to the DefaultPool type. To use a GameObject pool, implement IPunPrefabPool and assign it here. Prefabs are identified by name.

int QuickResends
staticgetset

In case of network loss, reliable messages can be repeated quickly up to 3 times.

When reliable messages get lost more than once, subsequent repeats are delayed a bit to allow the network to recover.
With this option, the repeats 2 and 3 can be sped up. This can help avoid timeouts but also it increases the speed in which gaps are closed.
When you set this, increase PhotonNetwork.MaxResendsBeforeDisconnect to 6 or 7.

int ResentReliableCommands
staticget

Count of commands that got repeated (due to local repeat-timing before an ACK was received).

If this value increases a lot, there is a good chance that a timeout disconnect will happen due to bad conditions.

int SendRate
staticgetset

Defines how many times per second PhotonNetwork should send a package. If you change this, do not forget to also change 'SerializationRate'.

Less packages are less overhead but more delay. Setting the SendRate to 50 will create up to 50 packages per second (which is a lot!). Keep your target platform in mind: mobile networks are slower and less reliable.

int SerializationRate
staticgetset

Defines how many times per second OnPhotonSerialize should be called on PhotonViews.

Choose this value in relation to PhotonNetwork.SendRate. OnPhotonSerialize will create updates and messages to be sent.
A lower rate takes up less performance but will cause more lag.

ServerConnection Server
staticget

The server (type) this client is currently connected or connecting to.

Photon uses 3 different roles of servers: Name Server, Master Server and Game Server.

string ServerAddress
staticget

Currently used server address (no matter if master or game server).

int ServerTimestamp
staticget

The current server's millisecond timestamp.

This can be useful to sync actions and events on all clients in one room. The timestamp is based on the server's Environment.TickCount.

It will overflow from a positive to a negative value every so often, so be careful to use only time-differences to check the Time delta when things happen.

This is the basis for PhotonNetwork.Time.

double Time
staticget

Photon network time, synched with the server.

v1.55
This time value depends on the server's Environment.TickCount. It is different per server but inside a Room, all clients should have the same value (Rooms are on one server only).
This is not a DateTime!

Use this value with care:
It can start with any positive value.
It will "wrap around" from 4294967.295 to 0!

bool UseAlternativeUdpPorts
staticgetset

Switch to alternative ports for a UDP connection to the Public Cloud.

This should be used when a customer has issues with connection stability. Some players reported better connectivity for Steam games. The effect might vary, which is why the alternative ports are not the new default.

The alternative (server) ports are 27000 up to 27003.

The values are appplied by replacing any incoming server-address string accordingly. You only need to set this to true though.

This value does not affect TCP or WebSocket connections.

Online Documentation  -  Dashboard  -  Support Forum Exit Games GmbH