Photon Unity Networking 2 2.45

Classes | Static Public Member Functions | Static Public Attributes | Properties | List of all members
PhotonNetwork Class Reference

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 ConnectUsingSettings (AppSettings appSettings, bool startInOfflineMode=false)
 
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, which happens if EnableCloseConnection is set to true. 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 JoinRandomOrCreateRoom (Hashtable expectedCustomRoomProperties=null, byte expectedMaxPlayers=0, MatchmakingMode matchingType=MatchmakingMode.FillRoom, TypedLobby typedLobby=null, string sqlLobbyFilter=null, string roomName=null, RoomOptions roomOptions=null, string[] expectedUsers=null)
 Attempts to join a room that matches the specified filter and creates a room if none found. 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 (non-empty) SQL-like filter. Triggers OnRoomListUpdate callback. More...
 
static bool 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)
 
static bool AllocateRoomViewID (PhotonView view)
 Enables the Master Client to allocate a viewID for room objects. More...
 
static int AllocateViewID (bool roomObject)
 Allocates a viewID for the current/local player or the room. More...
 
static int AllocateViewID (int ownerId)
 Allocates a viewID for the current/local player or the room. 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 GameObject InstantiateRoomObject (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 LoadOrCreateSettings (bool reload=false)
 
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 bool RemoveBufferedRPCs (int viewId=0, string methodName=null, int[] callersActorNumbers=null)
 Clear buffered RPCs based on filter parameters. 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...
 

Static Public Attributes

const string PunVersion = "2.45"
 Version number of PUN. Used in the AppVersion, which separates your playerbase in matchmaking. More...
 
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...
 
const string ServerSettingsFileName = "PhotonServerSettings"
 Name of the PhotonServerSettings file (used to load and by PhotonEditor to save new files). 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 bool EnableCloseConnection = false
 Used to enable reaction to CloseConnection events. Default: false. 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 float MinimalTimeScaleToDispatchInFixedUpdate = -1f
 Affects if the PhotonHandler dispatches incoming messages in LateUpdate or FixedUpdate (default). More...
 
static bool UseRpcMonoBehaviourCache
 While enabled, the MonoBehaviours on which we call RPCs are cached, avoiding costly GetComponents<MonoBehaviour>() calls. More...
 
static bool RunRpcCoroutines = true
 If an RPC method is implemented as coroutine, it gets started, unless this value is false. More...
 
static int ObjectsInOneUpdate = 20
 Defines how many updated produced by OnPhotonSerialize() are batched into one message. More...
 
const int SyncViewId = 0
 
const int SyncCompressed = 1
 
const int SyncNullValues = 2
 
const int SyncFirstValue = 3
 

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 specify the "Virtual AppId". More...
 
static ServerSettings PhotonServerSettings [get]
 Serialized server settings, written by the Setup Wizard for use in ConnectUsingSettings. 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? CurrentCluster [get]
 The cluster name provided by the Name Server. 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 immediately after Connect-call, 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 ClientStateNetworkClientState [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 AuthenticationValuesAuthValues [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 RoomCurrentRoom [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 the PhotonHandler should send data, if any is queued. Default: 30. More...
 
static int SerializationRate [get, set]
 Defines how many times per second OnPhotonSerialize should be called on PhotonViews for controlled objects. More...
 
static bool IsMessageQueueRunning [get, set]
 Can be used to pause dispatching of incoming events (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 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]
 Replaced by ServerPortOverrides. More...
 
static PhotonPortDefinitionServerPortOverrides [get, set]
 Defines overrides for server ports. Used per server-type if > 0. Important: If you change the transport protocol, adjust the overrides, too. More...
 
static PhotonView[] PhotonViews [get]
 Gets the photon views. More...
 
static NonAllocDictionary< int, PhotonView >.ValueIterator PhotonViewCollection [get]
 Returns a new iterable collection of current photon views. More...
 
static int ViewCount [get]
 
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

◆ AddCallbackTarget()

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.

◆ AllocateRoomViewID()

static bool AllocateRoomViewID ( PhotonView  view)
static

Enables the Master Client to allocate a viewID for room objects.

Returns
True if a viewId was assigned. False if the PhotonView already had a non-zero viewID or if this client is not the Master Client.

◆ AllocateViewID() [1/3]

static int AllocateViewID ( bool  roomObject)
static

Allocates a viewID for the current/local player or the room.

Parameters
roomObjectUse true, to allocate a room viewID and false to allocate a viewID for the local player.
Returns
Returns a viewID (combined owner and sequential number) that can be assigned as PhotonView.ViewID.

◆ AllocateViewID() [2/3]

static int AllocateViewID ( int  ownerId)
static

Allocates a viewID for the current/local player or the room.

Parameters
ownerIdActorNumber to allocate a viewID for.
Returns
Returns a viewID (combined owner and sequential number) that can be assigned as PhotonView.ViewID.

◆ AllocateViewID() [3/3]

static bool AllocateViewID ( PhotonView  view)
static

Allocates a viewID for the current/local player.

Returns
True if a viewId was assigned. False if the PhotonView already had a non-zero viewID.

◆ CloseConnection()

static bool CloseConnection ( Player  kickPlayer)
static

Request a client to disconnect/kick, which happens if EnableCloseConnection is set to true. Only the master client can do this.

Only the target player gets this event. That player will disconnect if EnableCloseConnection = true.

Parameters
kickPlayerThe Player to kick.

◆ ConnectToBestCloudServer()

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.

◆ ConnectToMaster()

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).

◆ ConnectToRegion()

static bool ConnectToRegion ( string  region)
static

Connects to the Photon Cloud region of choice.

It's typically enough to define the region code ("eu", "us", etc). Connecting to a specific cluster may be necessary, when regions get sharded and you support friends / invites.

In all other cases, you should not define a cluster as this allows the Name Server to distribute clients as needed. A random, load balanced cluster will be selected.

The Name Server has the final say to assign a cluster as available. If the requested cluster is not available another will be assigned.

Once connected, check the value of CurrentCluster.

◆ ConnectUsingSettings()

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).

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.

◆ CreateRoom()

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.

◆ Destroy() [1/2]

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.
  • Room-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.

◆ Destroy() [2/2]

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.
  • Room-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.

◆ DestroyAll()

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.

◆ DestroyPlayerObjects() [1/3]

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.

◆ DestroyPlayerObjects() [2/3]

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.

◆ DestroyPlayerObjects() [3/3]

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.

◆ Disconnect()

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.

◆ FetchServerTimestamp()

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.

◆ FindFriends()

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.

◆ FindGameObjectsWithComponent()

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.

◆ GetCustomRoomList()

static bool GetCustomRoomList ( TypedLobby  typedLobby,
string  sqlLobbyFilter 
)
static

Fetches a custom list of games from the server, matching a (non-empty) SQL-like filter. Triggers OnRoomListUpdate callback.

Operation is only available for lobbies of type SqlLobby and the filter can not be empty. It will check those conditions and fail locally, returning false. 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.

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).

◆ GetPing()

static int GetPing ( )
static

The current roundtrip time to the photon server.

Returns
Roundtrip time (to server and back).

◆ JoinLobby() [1/2]

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!

◆ JoinLobby() [2/2]

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).

◆ JoinOrCreateRoom()

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.

◆ JoinRandomOrCreateRoom()

static bool JoinRandomOrCreateRoom ( Hashtable  expectedCustomRoomProperties = null,
byte  expectedMaxPlayers = 0,
MatchmakingMode  matchingType = MatchmakingMode.FillRoom,
TypedLobby  typedLobby = null,
string  sqlLobbyFilter = null,
string  roomName = null,
RoomOptions  roomOptions = null,
string[]  expectedUsers = null 
)
static

Attempts to join a room that matches the specified filter and creates a room if none found.

This operation is a combination of filter-based random matchmaking with the option to create a new room, if no fitting room exists. The benefit of that is that the room creation is done by the same operation and the room can be found by the very next client, looking for similar rooms.

There are separate parameters for joining and creating a room.

This method can only be called while connected to a Master Server. This client's State is set to ClientState.Joining immediately.

Either IMatchmakingCallbacks.OnJoinedRoom or IMatchmakingCallbacks.OnCreatedRoom gets called.

Should the creation on the Master Server, IMatchmakingCallbacks.OnJoinRandomFailed gets called. Should the "join" on the Game Server fail, IMatchmakingCallbacks.OnJoinRoomFailed gets called.

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.

Returns
If the operation will be sent (requires connection to Master Server).

◆ JoinRandomRoom() [1/3]

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

◆ JoinRandomRoom() [2/3]

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.

◆ JoinRandomRoom() [3/3]

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.

◆ JoinRoom()

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.

◆ LeaveLobby()

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.

◆ LeaveRoom()

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.

◆ LoadLevel() [1/2]

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.

◆ LoadLevel() [2/2]

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.

◆ NetworkStatisticsReset()

static void NetworkStatisticsReset ( )
static

Resets the traffic stats and re-enables them.

◆ NetworkStatisticsToString()

static string NetworkStatisticsToString ( )
static

Only available when NetworkStatisticsEnabled was used to gather some stats.

Returns
A string with vital networking statistics.

◆ OpCleanActorRpcBuffer()

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

◆ OpCleanRpcBuffer()

static void OpCleanRpcBuffer ( PhotonView  view)
static

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

◆ OpRemoveCompleteCacheOfPlayer()

static void OpRemoveCompleteCacheOfPlayer ( int  actorNumber)
static

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

Parameters
actorNumber

◆ RaiseEvent()

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.

◆ Reconnect()

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.

◆ ReconnectAndRejoin()

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.

◆ RejoinRoom()

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.

◆ RemoveBufferedRPCs()

static bool RemoveBufferedRPCs ( int  viewId = 0,
string  methodName = null,
int[]  callersActorNumbers = null 
)
static

Clear buffered RPCs based on filter parameters.

Parameters
viewIdThe viewID of the PhotonView where the RPC has been called on. We actually need its ViewID. If 0 (default) is provided, all PhotonViews/ViewIDs are considered.
methodNameThe RPC method name, if possible we will use its hash shortcut for efficiency. If none (null or empty string) is provided all RPC method names are considered.
callersActorNumbersThe actor numbers of the players who called/buffered the RPC. For example if two players buffered the same RPC you can clear the buffered RPC of one and keep the other. If none (null or empty array) is provided all senders are considered.
Returns
If the operation could be sent to the server.

◆ RemoveCallbackTarget()

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.

◆ RemovePlayerCustomProperties()

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.

◆ RemoveRPCs() [1/2]

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.

◆ RemoveRPCs() [2/2]

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.

◆ RemoveRPCsInGroup()

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.

◆ SendAllOutgoingCommands()

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.

◆ SetInterestGroups() [1/2]

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).

◆ SetInterestGroups() [2/2]

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).

◆ SetLevelPrefix()

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

◆ SetMasterClient()

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).

◆ SetPlayerCustomProperties()

static bool 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.
Returns
False if customProperties is empty or have zero string keys. True in offline mode. True if not in a room and this is the local player (use this to cache properties to be sent when joining a room). Otherwise, returns if this operation could be sent to the server.

◆ SetSendingEnabled() [1/2]

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).

◆ SetSendingEnabled() [2/2]

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).

◆ WebRpc()

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. 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 = 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.

◆ EnableCloseConnection

bool EnableCloseConnection = false
static

Used to enable reaction to CloseConnection events. Default: false.

Using CloseConnection is a security risk, as exploiters can send the event as Master Client.

In best case, a game would implement this "disconnect others" independently from PUN in game-code with some security checks.

◆ LogLevel

Controls how verbose PUN is.

◆ MAX_VIEW_IDS

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.

◆ MinimalTimeScaleToDispatchInFixedUpdate

float MinimalTimeScaleToDispatchInFixedUpdate = -1f
static

Affects if the PhotonHandler dispatches incoming messages in LateUpdate or FixedUpdate (default).

By default the PhotonHandler component dispatches incoming messages in FixedUpdate.

When the Time.timeScale is low, FixedUpdate is called less frequently up to a point where updates may get paused. PUN can automatically dispatch messages in LateUpdate for low timeScale values (when Time.timeScale is lower than this value).

PUN will use either FixedUpdate or LateUpdate but not both (as of v2.23).

When you use this value, be aware that Instantiates and RPCs execute with a changed timing within a frame. If Instantiate is called from FixedUpdate, the physics engine seems to run for instantiated objects before the engine calls Start() on them.

By default, this value is -1f, so there is no fallback to LateUpdate.

◆ NetworkingClient

LoadBalancingClient NetworkingClient
static

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

◆ ObjectsInOneUpdate

int ObjectsInOneUpdate = 20
static

Defines how many updated produced by OnPhotonSerialize() are batched into one message.

A low number increases overhead, a high number might lead to fragmented messages.

◆ PrecisionForFloatSynchronization

float PrecisionForFloatSynchronization = 0.01f
static

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

◆ PrecisionForQuaternionSynchronization

float PrecisionForQuaternionSynchronization = 1.0f
static

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

◆ PrecisionForVectorSynchronization

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.

◆ PunVersion

const string PunVersion = "2.45"
static

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

◆ RunRpcCoroutines

bool RunRpcCoroutines = true
static

If an RPC method is implemented as coroutine, it gets started, unless this value is false.

As starting coroutines causes a little memnory garbage, you may want to disable this option but it is also good enough to not return IEnumerable from methods with the attribute PunRPC.

◆ ServerSettingsFileName

const string ServerSettingsFileName = "PhotonServerSettings"
static

Name of the PhotonServerSettings file (used to load and by PhotonEditor to save new files).

◆ UseRpcMonoBehaviourCache

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

◆ AppVersion

string AppVersion
staticget

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

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

◆ AuthValues

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.

◆ AutomaticallySyncScene

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.

◆ BestRegionSummaryInPreferences

string BestRegionSummaryInPreferences
staticgetset

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

Set this value to null before you connect, to discard the previously selected Best Region for the client.

◆ CloudRegion

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.

◆ CountOfPlayers

int CountOfPlayers
staticget

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

◆ CountOfPlayersInRooms

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!

◆ CountOfPlayersOnMaster

int CountOfPlayersOnMaster
staticget

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

◆ CountOfRooms

int CountOfRooms
staticget

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

◆ CrcCheckEnabled

bool CrcCheckEnabled
staticgetset

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

◆ CurrentCluster

string? CurrentCluster
staticget

The cluster name provided by the Name Server.

The value is provided by the OpResponse for OpAuthenticate/OpAuthenticateOnce. See ConnectToRegion.

Null until set.

Note that the Name Server may assign another cluster, if the requested one is not configured or available.

◆ CurrentLobby

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)

◆ CurrentRoom

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

◆ EnableLobbyStatistics

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.

◆ GameVersion

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.

◆ InLobby

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).

◆ InRoom

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.

◆ IsConnected

bool IsConnected
staticget

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

It is recommended to use the IConnectionCallbacks to establish a connection workflow. Also have a look at IsConnectedAndReady, which provides more info on when you can call operations at all.

◆ IsConnectedAndReady

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.

◆ IsMasterClient

bool IsMasterClient
staticget

Are we the master client?

◆ IsMessageQueueRunning

bool IsMessageQueueRunning
staticgetset

Can be used to pause dispatching of incoming events (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.

◆ KeepAliveInBackground

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.

◆ LevelLoadingProgress

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.

◆ LocalPlayer

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.

◆ MasterClient

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.

◆ MaxResendsBeforeDisconnect

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.

◆ NetworkClientState

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.

◆ NetworkStatisticsEnabled

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

◆ NickName

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.

◆ OfflineMode

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

◆ PacketLossByCrcCheck

int PacketLossByCrcCheck
staticget

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

◆ PhotonServerSettings

ServerSettings PhotonServerSettings
staticget

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

◆ PhotonViewCollection

NonAllocDictionary<int, PhotonView>.ValueIterator PhotonViewCollection
staticget

Returns a new iterable collection of current photon views.

You can iterate over all PhotonViews in a simple foreach loop. To use this in a while-loop, assign the new iterator to a variable and then call MoveNext on that.

◆ PhotonViews

PhotonView [] PhotonViews
staticget

Gets the photon views.

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

The photon views.

◆ PlayerList

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.

◆ PlayerListOthers

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.

◆ PrefabPool

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.

◆ QuickResends

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.

◆ ResentReliableCommands

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.

◆ SendRate

int SendRate
staticgetset

Defines how many times per second the PhotonHandler should send data, if any is queued. Default: 30.

This value defines how often PUN will call the low level PhotonPeer to put queued outgoing messages into a datagram to be sent. This is implemented in the PhotonHandler component, which integrates PUN into the Unity game loop. The PhotonHandler.MaxDatagrams value defines how many datagrams can be sent in one iteration.

This value does not affect how often updates are written by PhotonViews. That is controlled by the SerializationRate. To avoid send-delays for PhotonView updates, PUN will also send data at the end of frames that wrote data in OnPhotonSerializeView, so sending may actually be more frequent than the SendRate.

Messages queued due to RPCs and RaiseEvent, will be sent with at least SendRate frequency. They are included, when OnPhotonSerialize wrote updates and triggers early sending.

Setting this value does not adjust the SerializationRate anymore (as of PUN 2.24).

Sending less often will aggregate messages in datagrams, which avoids overhead on the network. It is also important to not push too many datagrams per frame. Three to five seem to be the sweet spot.

Keep your target platform in mind: mobile networks are usually slower. WiFi is slower with more variance and bursts of loss.

A low framerate (as in Update calls) will affect sending of messages.

◆ SerializationRate

int SerializationRate
staticgetset

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

This value defines how often PUN will call OnPhotonSerialize on controlled network objects. This is implemented in the PhotonHandler component, which integrates PUN into the Unity game loop.

The updates written in OnPhotonSerialize will be queued temporarily and sent in the next LateUpdate, so a high SerializationRate also causes more sends. The idea is to keep the delay short during which written updates are queued.

Calling RPCs will not trigger a send.

A low framerate will affect how frequent updates are written and how "on time" they are.

A lower rate takes up less performance but the receiving side needs to interpolate longer times between updates.

◆ Server

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.

◆ ServerAddress

string? ServerAddress
staticget

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

◆ ServerPortOverrides

PhotonPortDefinition? ServerPortOverrides
staticgetset

Defines overrides for server ports. Used per server-type if > 0. Important: If you change the transport protocol, adjust the overrides, too.

LoadBalancingClient.ServerPortOverrides

◆ ServerTimestamp

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.

◆ 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!

◆ UseAlternativeUdpPorts

bool UseAlternativeUdpPorts
staticgetset

Replaced by ServerPortOverrides.