Photon Unity Networking  v1.91
English | 日本語 | 한국
Public Member Functions | Static Public Member Functions | Public Attributes | Static Public Attributes | Properties | Events | List of all members
PhotonNetwork Class Reference

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

Public Member Functions

delegate void EventCallback (byte eventCode, object content, int senderId)
 Defines the delegate usable in OnEventCall. More...
 

Static Public Member Functions

static void SwitchToProtocol (ConnectionProtocol cp)
 While offline, the network protocol can be switched (which affects the ports you can use to connect). More...
 
static bool ConnectUsingSettings (string gameVersion)
 Connect to Photon as configured in the editor (saved in PhotonServerSettings file). More...
 
static bool ConnectToMaster (string masterServerAddress, int port, string appID, string gameVersion)
 Connect to a Photon Master Server by address, port, appID and game(client) version. More...
 
static bool Reconnect ()
 Can be used to reconnect to the master server after a disconnect. More...
 
static bool ReconnectAndRejoin ()
 When the client lost connection during gameplay, this method attempts to reconnect and rejoin the room. More...
 
static bool ConnectToBestCloudServer (string gameVersion)
 Connect to the Photon Cloud region with the lowest ping (on platforms that support Unity's Ping). More...
 
static bool ConnectToRegion (CloudRegionCode region, string gameVersion)
 Connects to the Photon Cloud region of choice. More...
 
static void OverrideBestCloudServer (CloudRegionCode region)
 Overwrites the region that is used for ConnectToBestCloudServer(string gameVersion). More...
 
static void RefreshCloudServerRating ()
 Pings all cloud servers again to find the one with best ping (currently). 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 void InitializeSecurity ()
 Used for compatibility with Unity networking only. Encryption is automatically initialized while connecting. More...
 
static void Disconnect ()
 Makes this client disconnect from the photon server, a process that leaves any room and calls OnDisconnectedFromPhoton on completion. 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 CreateRoom (string roomName)
 Creates a room with given name but fails if this room(name) is existing already. Creates random name for roomName null. More...
 
static bool CreateRoom (string roomName, RoomOptions roomOptions, TypedLobby typedLobby)
 Creates a room but fails if this room is existing already. Can only be called on Master Server. More...
 
static bool CreateRoom (string roomName, RoomOptions roomOptions, TypedLobby typedLobby, string[] expectedUsers)
 Creates a room but fails if this room is existing already. Can only be called on Master Server. More...
 
static bool JoinRoom (string roomName)
 Join room by roomname and on success calls OnJoinedRoom(). This is not affected by lobbies. More...
 
static bool JoinRoom (string roomName, string[] expectedUsers)
 Join room by roomname and on success calls OnJoinedRoom(). This is not affected by lobbies. More...
 
static bool JoinOrCreateRoom (string roomName, RoomOptions roomOptions, TypedLobby typedLobby)
 Lets you either join a named room or create it on the fly - you don't have to know if someone created the room already. More...
 
static bool JoinOrCreateRoom (string roomName, RoomOptions roomOptions, TypedLobby typedLobby, string[] expectedUsers)
 Lets you either join a named room or create it on the fly - you don't have to know if someone created the room already. More...
 
static bool JoinRandomRoom ()
 Joins any available room of the currently used lobby and fails if none is available. More...
 
static bool JoinRandomRoom (Hashtable expectedCustomRoomProperties, byte expectedMaxPlayers)
 Attempts to join an open room with fitting, custom properties but fails if none is currently available. More...
 
static bool JoinRandomRoom (Hashtable expectedCustomRoomProperties, byte expectedMaxPlayers, MatchmakingMode matchingType, TypedLobby typedLobby, string sqlLobbyFilter, string[] expectedUsers=null)
 Attempts to join an open room with fitting, custom properties but fails if none is currently available. More...
 
static bool ReJoinRoom (string roomName)
 Can be used to return to a room after a disconnect and reconnect. 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 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 GetCustomRoomList (TypedLobby typedLobby, string sqlLobbyFilter)
 Fetches a custom list of games from the server, matching a SQL-like "where" clause, then triggers OnReceivedRoomListUpdate callback. More...
 
static RoomInfo[] GetRoomList ()
 Gets currently cached rooms of the last rooms list sent by the server as RoomInfo array. This list is either available and updated automatically and periodically while in a lobby (check insideLobby) or received as a response to PhotonNetwork.GetCustomRoomList(). 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, bool sendReliable, RaiseEventOptions options)
 Sends fully customizable events in a room. Events consist of at least an EventCode (0..199) and can have content. More...
 
static int AllocateViewID ()
 Allocates a viewID that's valid for the current/local player. More...
 
static int AllocateSceneViewID ()
 Enables the Master Client to allocate a viewID that is valid for scene objects. More...
 
static void UnAllocateViewID (int viewID)
 Unregister a viewID (of manually instantiated and destroyed networked objects). More...
 
static GameObject Instantiate (string prefabName, Vector3 position, Quaternion rotation, byte group)
 Instantiate a prefab over the network. This prefab needs to be located in the root of a "Resources" folder. More...
 
static GameObject Instantiate (string prefabName, Vector3 position, Quaternion rotation, byte group, object[] data)
 Instantiate a prefab over the network. This prefab needs to be located in the root of a "Resources" folder. More...
 
static GameObject InstantiateSceneObject (string prefabName, Vector3 position, Quaternion rotation, byte group, object[] data)
 Instantiate a scene-owned prefab over the network. The PhotonViews will be controllable by the MasterClient. This prefab needs to be located in the root of a "Resources" folder. 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 SendOutgoingCommands ()
 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 (PhotonPlayer kickPlayer)
 Request a client to disconnect (KICK). Only the master client can do this More...
 
static bool SetMasterClient (PhotonPlayer masterClientPlayer)
 Asks the server to assign another player as Master Client of your current room. More...
 
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 (PhotonPlayer 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 (PhotonPlayer 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 void RemoveRPCsInGroup (int targetGroup)
 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 CacheSendMonoMessageTargets (Type type)
 Populates SendMonoMessageTargets with currently existing GameObjects that have a Component of type. More...
 
static HashSet< GameObject > FindGameObjectsWithComponent (Type type)
 Finds the GameObjects with Components of a specific type (using FindObjectsOfType). More...
 
static void SetReceivingEnabled (int group, bool enabled)
 
static void SetInterestGroups (byte group, bool enabled)
 Enable/disable receiving events from a given Interest Group. More...
 
static void SetReceivingEnabled (int[] enableGroups, int[] disableGroups)
 
static void SetInterestGroups (byte[] disableGroups, byte[] enableGroups)
 Enable/disable receiving on given Interest Groups (applied to PhotonViews). More...
 
static void SetSendingEnabled (int group, bool enabled)
 
static void SetSendingEnabled (byte group, bool enabled)
 Enable/disable sending on given group (applied to PhotonViews) More...
 
static void SetSendingEnabled (int[] enableGroups, int[] disableGroups)
 
static void SetSendingEnabled (byte[] disableGroups, byte[] enableGroups)
 Enable/disable sending on given groups (applied to PhotonViews) More...
 
static void SetLevelPrefix (short prefix)
 Sets level prefix for PhotonViews instantiated later on. Don't set it if you need only one! More...
 
static void LoadLevel (int levelNumber)
 Wraps loading a level to pause the network message-queue. Optionally syncs the loaded level in a room. More...
 
static AsyncOperation LoadLevelAsync (int levelNumber)
 Wraps single asynchronous loading of a level to pause the network message-queue. Optionally syncs the loaded level in a room. More...
 
static void LoadLevel (string levelName)
 Wraps loading a level to pause the network message-queue. Optionally syncs the loaded level in a room. More...
 
static AsyncOperation LoadLevelAsync (string levelName)
 Wraps single asynchronous loading of a level to pause the network message-queue. Optionally syncs the loaded level in a room. More...
 
static bool WebRpc (string name, object parameters)
 This operation makes Photon call your custom web-service by name (path) with the given parameters. More...
 
static bool CallEvent (byte eventCode, object content, int senderId)
 

Public Attributes

const string versionPUN = "1.91"
 Version number of PUN. Also used in GameVersion to separate client version from each other. More...
 

Static Public Attributes

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.serverSettingsAssetFile, typeof(ServerSettings))
 Serialized server settings, written by the Setup Wizard for use in ConnectUsingSettings. More...
 
static bool InstantiateInRoomOnly = true
 If true, Instantiate methods will check if you are in a room and fail if you are not. More...
 
static PhotonLogLevel logLevel = PhotonLogLevel.ErrorsOnly
 Network log level. 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 bool UsePrefabCache = true
 While enabled (true), Instantiate uses PhotonNetwork.PrefabCache to keep game objects in memory (improving instantiation of the same prefab). More...
 
static Dictionary< string,
GameObject > 
PrefabCache = new Dictionary<string, GameObject>()
 Keeps references to GameObjects for frequent instantiation (out of memory instead of loading the Resources). More...
 
static HashSet< GameObject > SendMonoMessageTargets
 If not null, this is the (exclusive) list of GameObjects that get called by PUN SendMonoMessage(). More...
 
static Type SendMonoMessageTargetType = typeof(MonoBehaviour)
 Defines which classes can contain PUN Callback implementations. More...
 
static bool StartRpcsAsCoroutine = true
 Can be used to skip starting RPCs as Coroutine, which can be a performance issue. More...
 
static int maxConnections
 Only used in Unity Networking. In PUN, set the number of players in PhotonNetwork.CreateRoom. More...
 
static float BackgroundTimeout = 60.0f
 Defines how many seconds PUN keeps the connection, after Unity's OnApplicationPause(true) call. Default: 60 seconds. More...
 

Properties

static string gameVersion [get, set]
 Version string for your this build. Can be used to separate incompatible clients. Sent during connect. More...
 
static string ServerAddress [get]
 Currently used server address (no matter if master or game server). More...
 
static CloudRegionCode 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 bool connected [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 connecting [get]
 True when you called ConnectUsingSettings (or similar) until the low level connection to Photon gets established. More...
 
static bool connectedAndReady [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 ConnectionState connectionState [get]
 Simplified connection state More...
 
static ClientState connectionStateDetailed [get]
 Detailed connection state (ignorant of PUN, so it can be "disconnected" while switching servers). 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 Room room [get]
 Get the room we're currently in. Null if we aren't in any room. More...
 
static PhotonPlayer player [get]
 The local PhotonPlayer. Always available and represents this player. CustomProperties can be set before entering a room and will be synced as well. More...
 
static PhotonPlayer masterClient [get]
 The Master Client of the current room or null (outside of rooms). More...
 
static string playerName [get, set]
 Set to synchronize the player's nickname with everyone in the room(s) you enter. This sets PhotonNetwork.player.NickName. More...
 
static PhotonPlayer[] playerList [get]
 The list of players in the current room, including the local player. More...
 
static PhotonPlayer[] otherPlayers [get]
 The list of players in the current room, excluding the local player. More...
 
static List< FriendInfoFriends [get, set]
 Read-only list of friends, their online status and the room they are in. Null until initialized by a FindFriends call. More...
 
static int FriendsListAge [get]
 Age of friend list info (in milliseconds). It's 0 until a friend list is fetched. More...
 
static IPunPrefabPool PrefabPool [get, set]
 An Object Pool can be used to keep and reuse instantiated object instances. It replaced Unity's default Instantiate and Destroy methods. 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 load the same level as the Master Client (if that used PhotonNetwork.LoadLevel). More...
 
static bool autoCleanUpPlayerObjects [get, set]
 This setting defines per room, if network-instantiated GameObjects (with PhotonView) get cleaned up when the creator of it leaves. More...
 
static bool autoJoinLobby [get, set]
 Set in PhotonServerSettings asset. Defines if the PhotonNetwork should join the "lobby" when connected to the Master server. More...
 
static bool EnableLobbyStatistics [get, set]
 Set in PhotonServerSettings asset. Enable to get a list of active lobbies from the Master Server. More...
 
static List< TypedLobbyInfoLobbyStatistics [get, set]
 If turned on, the Master Server will provide information about active lobbies for this application. More...
 
static bool insideLobby [get]
 True while this client is in a lobby. More...
 
static TypedLobby lobby [get, set]
 The lobby that will be used when PUN joins a lobby or creates a game. 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 'sendRateOnSerialize'. More...
 
static int sendRateOnSerialize [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 int unreliableCommandsLimit [get, set]
 Used once per dispatch to limit unreliable commands per channel (so after a pause, many channels can still cause a lot of unreliable commands) 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 bool isMasterClient [get]
 Are we the master client? More...
 
static bool inRoom [get]
 Is true while being in a room (connectionStateDetailed == ClientState.Joined). More...
 
static bool isNonMasterClientInRoom [get]
 True if we are in a room (client) and NOT the room's masterclient 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.room.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...
 

Events

static EventCallback OnEventCall
 Register your RaiseEvent handling methods here by using "+=". More...
 

Detailed Description

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

Member Function Documentation

static int PhotonNetwork.AllocateSceneViewID ( )
static

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

Returns
A viewID that can be used for a new PhotonView or -1 in case of an error.
static int PhotonNetwork.AllocateViewID ( )
static

Allocates a viewID that's valid for the current/local player.

Returns
A viewID that can be used for a new PhotonView.
static void PhotonNetwork.CacheSendMonoMessageTargets ( Type  type)
static

Populates SendMonoMessageTargets with currently existing GameObjects that have a Component of type.

Parameters
typeIf null, this will use SendMonoMessageTargets as component-type (MonoBehaviour by default).
static bool PhotonNetwork.CallEvent ( byte  eventCode,
object  content,
int  senderId 
)
static
static bool PhotonNetwork.CloseConnection ( PhotonPlayer  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 PhotonPlayer to kick.
static bool PhotonNetwork.ConnectToBestCloudServer ( string  gameVersion)
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://www.photonengine.com/dashboard

Connecting to the Photon Cloud might fail due to:

Parameters
gameVersionThis client's version number. Users are separated from each other by gameversion (which allows you to make breaking changes).
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 PhotonNetwork.ConnectToMaster ( string  masterServerAddress,
int  port,
string  appID,
string  gameVersion 
)
static

Connect to a Photon Master Server by address, port, appID and game(client) version.

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

Connecting to the Photon Cloud might fail due to:

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).
gameVersionThis client's version number. Users are separated by gameversion (which allows you to make breaking changes).
static bool PhotonNetwork.ConnectToRegion ( CloudRegionCode  region,
string  gameVersion 
)
static

Connects to the Photon Cloud region of choice.

static bool PhotonNetwork.ConnectUsingSettings ( string  gameVersion)
static

Connect to Photon as configured in the editor (saved in PhotonServerSettings file).

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

Your server configuration is created by the PUN Wizard and contains the AppId and region for Photon Cloud games and the server address if you host Photon yourself. These settings usually don't change often.

To ignore the config file and connect anywhere call: PhotonNetwork.ConnectToMaster.

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

Connecting to the Photon Cloud might fail due to:

Parameters
gameVersionThis client's version number. Users are separated from each other by gameversion (which allows you to make breaking changes).
static bool PhotonNetwork.CreateRoom ( string  roomName)
static

Creates a room with given name but fails if this room(name) is existing already. Creates random name for roomName null.

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

The created room is automatically placed in the currently used lobby (if any) or the default-lobby if you didn't explicitly join one.

Call this only on the master server. Internally, the master will respond with a server-address (and roomName, if needed). Both are used internally to switch to the assigned game server and roomName.

PhotonNetwork.autoCleanUpPlayerObjects will become this room's AutoCleanUp property and that's used by all clients that join this room.

Parameters
roomNameUnique name of the room to create.
Returns
If the operation got queued and will be sent.
static bool PhotonNetwork.CreateRoom ( string  roomName,
RoomOptions  roomOptions,
TypedLobby  typedLobby 
)
static

Creates a room but fails if this room is existing already. Can only be called on Master Server.

When successful, this calls the callbacks OnCreatedRoom and OnJoinedRoom (the latter, cause you join as first player). If the room can't be created (because it exists already), OnPhotonCreateRoomFailed gets called.

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

Rooms can be created in any number of lobbies. Those don't have to exist before you create a room in them (they get auto-created on demand). Lobbies can be useful to split room lists on the server-side already. That can help keep the room lists short and manageable. If you set a typedLobby parameter, the room will be created in that lobby (no matter if you are active in any). If you don't set a typedLobby, the room is automatically placed in the currently active lobby (if any) or the default-lobby.

Call this only on the master server. Internally, the master will respond with a server-address (and roomName, if needed). Both are used internally to switch to the assigned game server and roomName.

PhotonNetwork.autoCleanUpPlayerObjects will become this room's autoCleanUp property and that's used by all clients that join this room.

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).
Returns
If the operation got queued and will be sent.
static bool PhotonNetwork.CreateRoom ( string  roomName,
RoomOptions  roomOptions,
TypedLobby  typedLobby,
string[]  expectedUsers 
)
static

Creates a room but fails if this room is existing already. Can only be called on Master Server.

When successful, this calls the callbacks OnCreatedRoom and OnJoinedRoom (the latter, cause you join as first player). If the room can't be created (because it exists already), OnPhotonCreateRoomFailed gets called.

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

Rooms can be created in any number of lobbies. Those don't have to exist before you create a room in them (they get auto-created on demand). Lobbies can be useful to split room lists on the server-side already. That can help keep the room lists short and manageable. If you set a typedLobby parameter, the room will be created in that lobby (no matter if you are active in any). If you don't set a typedLobby, the room is automatically placed in the currently active lobby (if any) or the default-lobby.

Call this only on the master server. Internally, the master will respond with a server-address (and roomName, if needed). Both are used internally to switch to the assigned game server and roomName.

PhotonNetwork.autoCleanUpPlayerObjects will become this room's autoCleanUp property and that's used by all clients that join this room.

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.

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 PhotonNetwork.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 PhotonNetwork.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 PhotonNetwork.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 PhotonNetwork.DestroyPlayerObjects ( PhotonPlayer  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 PhotonNetwork.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 PhotonNetwork.Disconnect ( )
static

Makes this client disconnect from the photon server, a process that leaves any room and calls OnDisconnectedFromPhoton 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 OnDisconnectedFromPhoton are immediate. Offline mode is set to false as well. Once disconnected, the client can connect again. Use ConnectUsingSettings.

delegate void PhotonNetwork.EventCallback ( byte  eventCode,
object  content,
int  senderId 
)

Defines the delegate usable in OnEventCall.

Any eventCode < 200 will be forwarded to your delegate(s).

Parameters
eventCodeThe code assigend to the incoming event.
contentThe content the sender put into the event.
senderIdThe ID of the player who sent the event. It might be 0, if the "room" sent the event.
static void PhotonNetwork.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 PhotonNetwork.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 playerName 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> PhotonNetwork.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 PhotonNetwork.GetCustomRoomList ( TypedLobby  typedLobby,
string  sqlLobbyFilter 
)
static

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

Operation is only available for lobbies of type SqlLobby. Note: You don't have to join that lobby. This is an async request.

When done, OnReceivedRoomListUpdate gets called. Use GetRoomList() to access it.

https://doc.photonengine.com/en-us/pun/current/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 PhotonNetwork.GetPing ( )
static

The current roundtrip time to the photon server.

Returns
Roundtrip time (to server and back).
static RoomInfo [] PhotonNetwork.GetRoomList ( )
static

Gets currently cached rooms of the last rooms list sent by the server as RoomInfo array. This list is either available and updated automatically and periodically while in a lobby (check insideLobby) or received as a response to PhotonNetwork.GetCustomRoomList().

This list is a cached copy of the internal rooms list so it can be accessed each frame if needed. Per RoomInfo you can check if the room is full by comparing playerCount and MaxPlayers before you allow a join.

The name of a room must be used to join it (via JoinRoom).

Closed rooms are also listed by lobbies but they can't be joined. While in a room, any player can set Room.visible and Room.open to hide rooms from matchmaking and close them.

Returns
Cached RoomInfo[] of last room list sent by the server.
static void PhotonNetwork.InitializeSecurity ( )
static

Used for compatibility with Unity networking only. Encryption is automatically initialized while connecting.

static GameObject PhotonNetwork.Instantiate ( string  prefabName,
Vector3  position,
Quaternion  rotation,
byte  group 
)
static

Instantiate a prefab over the network. This prefab needs to be located in the root of a "Resources" folder.

Instead of using prefabs in the Resources folder, you can manually Instantiate and assign PhotonViews. See doc.

Parameters
prefabNameName of the prefab to instantiate.
positionPosition Vector3 to apply on instantiation.
rotationRotation Quaternion to apply on instantiation.
groupThe group for this PhotonView.
Returns
The new instance of a GameObject with initialized PhotonView.
static GameObject PhotonNetwork.Instantiate ( string  prefabName,
Vector3  position,
Quaternion  rotation,
byte  group,
object[]  data 
)
static

Instantiate a prefab over the network. This prefab needs to be located in the root of a "Resources" folder.

Instead of using prefabs in the Resources folder, you can manually Instantiate and assign PhotonViews. See doc.

Parameters
prefabNameName of the prefab to instantiate.
positionPosition Vector3 to apply on instantiation.
rotationRotation Quaternion to apply on instantiation.
groupThe group for this PhotonView.
dataOptional instantiation data. This will be saved to it's PhotonView.instantiationData.
Returns
The new instance of a GameObject with initialized PhotonView.
static GameObject PhotonNetwork.InstantiateSceneObject ( string  prefabName,
Vector3  position,
Quaternion  rotation,
byte  group,
object[]  data 
)
static

Instantiate a scene-owned prefab over the network. The PhotonViews will be controllable by the MasterClient. This prefab needs to be located in the root of a "Resources" folder.

Only the master client can Instantiate scene objects. Instead of using prefabs in the Resources folder, you can manually Instantiate and assign PhotonViews. See doc.

Parameters
prefabNameName of the prefab to instantiate.
positionPosition Vector3 to apply on instantiation.
rotationRotation Quaternion to apply on instantiation.
groupThe group for this PhotonView.
dataOptional instantiation data. This will be saved to it's PhotonView.instantiationData.
Returns
The new instance of a GameObject with initialized PhotonView.
static bool PhotonNetwork.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. You can access this cached list by PhotonNetwork.GetRoomList().

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/current/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! Set autoJoinLobby = false before you connect, to not join a lobby. In that case, the connect-workflow will call OnConnectedToMaster (if you implement it) when it's done.

static bool PhotonNetwork.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. You can access this cached list by PhotonNetwork.GetRoomList().

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: http://confluence.exitgames.com/display/PTN/Op+JoinRandomGame

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! Set autoJoinLobby = false before you connect, to not join a lobby. In that case, the connect-workflow will call OnConnectedToMaster (if you implement it) when it's done.

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

Lets you either join a named room or create it on the fly - you don't have to know if someone created the room already.

This makes it easier for groups of players to get into the same room. Once the group exchanged a roomName, any player can call JoinOrCreateRoom and it doesn't matter who actually joins or creates the room.

The parameters roomOptions and typedLobby are only used when the room actually gets created by this client. You know if this client created a room, if you get a callback OnCreatedRoom (before OnJoinedRoom gets called as well).

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.
Returns
If the operation got queued and will be sent.
static bool PhotonNetwork.JoinOrCreateRoom ( string  roomName,
RoomOptions  roomOptions,
TypedLobby  typedLobby,
string[]  expectedUsers 
)
static

Lets you either join a named room or create it on the fly - you don't have to know if someone created the room already.

This makes it easier for groups of players to get into the same room. Once the group exchanged a roomName, any player can call JoinOrCreateRoom and it doesn't matter who actually joins or creates the room.

The parameters roomOptions and typedLobby are only used when the room actually gets created by this client. You know if this client created a room, if you get a callback OnCreatedRoom (before OnJoinedRoom gets called as well).

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.

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 PhotonNetwork.JoinRandomRoom ( )
static

Joins any available room of the currently used lobby and fails if none is available.

Rooms can be created in arbitrary lobbies which get created on demand. You can join rooms from any lobby without actually joining the lobby. Use the JoinRandomRoom overload with TypedLobby parameter.

This method will only match rooms attached to one lobby! If you use many lobbies, you might have to repeat JoinRandomRoom, to find some fitting room. This method looks up a room in the currently active lobby or (if no lobby is joined) in the default lobby.

If this fails, you can still create a room (and make this available for the next who uses JoinRandomRoom). Alternatively, try again in a moment.

static bool PhotonNetwork.JoinRandomRoom ( Hashtable  expectedCustomRoomProperties,
byte  expectedMaxPlayers 
)
static

Attempts to join an open room with fitting, custom properties but fails if none is currently available.

Rooms can be created in arbitrary lobbies which get created on demand. You can join rooms from any lobby without actually joining the lobby. Use the JoinRandomRoom overload with TypedLobby parameter.

This method will only match rooms attached to one lobby! If you use many lobbies, you might have to repeat JoinRandomRoom, to find some fitting room. This method looks up a room in the currently active lobby or (if no lobby is joined) in the default lobby.

If this fails, you can still create a room (and make this available for the next who uses JoinRandomRoom). Alternatively, try again in a moment.

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 PhotonNetwork.JoinRandomRoom ( Hashtable  expectedCustomRoomProperties,
byte  expectedMaxPlayers,
MatchmakingMode  matchingType,
TypedLobby  typedLobby,
string  sqlLobbyFilter,
string[]  expectedUsers = null 
)
static

Attempts to join an open room with fitting, custom properties but fails if none is currently available.

Rooms can be created in arbitrary lobbies which get created on demand. You can join rooms from any lobby without actually joining the lobby with this overload.

This method will only match rooms attached to one lobby! If you use many lobbies, you might have to repeat JoinRandomRoom, to find some fitting room. This method looks up a room in the specified lobby or the currently active lobby (if none specified) or in the default lobby (if none active).

If this fails, you can still create a room (and make this available for the next who uses JoinRandomRoom). Alternatively, try again in a moment.

In offlineMode, a room will be created but no properties will be set and all parameters of this JoinRandomRoom call are ignored. The event/callback OnJoinedRoom gets called (see enum PhotonNetworkingMessage).

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.

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 PhotonNetwork.JoinRoom ( string  roomName)
static

Join room by roomname and on success calls OnJoinedRoom(). This is not affected by lobbies.

On success, the method OnJoinedRoom() is called on any script. You can implement it to react to joining a room.

JoinRoom fails if the room is either full or no longer available (it might become empty while you attempt to join). Implement OnPhotonJoinRoomFailed() to get a callback in error case.

To join a room from the lobby's listing, use RoomInfo.Name as roomName here. Despite using multiple lobbies, a roomName is always "global" for your application and so you don't have to specify which lobby it's in. The Master Server will find the room. In the Photon Cloud, an application is defined by AppId, Game- and PUN-version.

PhotonNetworkingMessage.OnPhotonJoinRoomFailed PhotonNetworkingMessage.OnJoinedRoom

Parameters
roomNameUnique name of the room to join.
Returns
If the operation got queued and will be sent.
static bool PhotonNetwork.JoinRoom ( string  roomName,
string[]  expectedUsers 
)
static

Join room by roomname and on success calls OnJoinedRoom(). This is not affected by lobbies.

On success, the method OnJoinedRoom() is called on any script. You can implement it to react to joining a room.

JoinRoom fails if the room is either full or no longer available (it might become empty while you attempt to join). Implement OnPhotonJoinRoomFailed() to get a callback in error case.

To join a room from the lobby's listing, use RoomInfo.Name as roomName here. Despite using multiple lobbies, a roomName is always "global" for your application and so you don't have to specify which lobby it's in. The Master Server will find the room. In the Photon Cloud, an application is defined by AppId, Game- and PUN-version.

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.

PhotonNetworkingMessage.OnPhotonJoinRoomFailed PhotonNetworkingMessage.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 PhotonNetwork.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. Use autoJoinLobby to not join a lobby when you connect.

static bool PhotonNetwork.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 PhotonNetwork.LoadLevel ( int  levelNumber)
static

Wraps loading a level to pause the network message-queue. Optionally syncs the loaded level in a room.

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.

While loading levels, it makes sense to not dispatch messages received by other players. This method takes care of that by setting PhotonNetwork.isMessageQueueRunning = false and enabling the queue when the level was loaded.

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

This uses Application.LoadLevel in Unity version not yet featuring the SceneManager API.

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

Wraps loading a level to pause the network message-queue. Optionally syncs the loaded level in a room.

While loading levels, it makes sense to not dispatch messages received by other players. This method takes care of that by setting PhotonNetwork.isMessageQueueRunning = false and enabling the queue when the level was 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.

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

This uses Application.LoadLevel in Unity version not yet featuring the SceneManager API.

Parameters
levelNameName of the level to load. Make sure it's available to all clients in the same room.
static AsyncOperation PhotonNetwork.LoadLevelAsync ( int  levelNumber)
static

Wraps single asynchronous loading of a level to pause the network message-queue. Optionally syncs the loaded level in a room.

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.

While loading levels, it makes sense to not dispatch messages received by other players. This method takes care of that by setting PhotonNetwork.isMessageQueueRunning = false and enabling the queue when the level was loaded.

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

This uses Application.LoadLevel in Unity version not yet featuring the SceneManager API.

Returns
The async operation.
Parameters
levelNumberNumber of the level to load. When using level numbers, make sure they are identical on all clients.
static AsyncOperation PhotonNetwork.LoadLevelAsync ( string  levelName)
static

Wraps single asynchronous loading of a level to pause the network message-queue. Optionally syncs the loaded level in a room.

While loading levels, it makes sense to not dispatch messages received by other players. This method takes care of that by setting PhotonNetwork.isMessageQueueRunning = false and enabling the queue when the level was 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.

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

This uses Application.LoadLevel in Unity version not yet featuring the SceneManager API.

Returns
The async operation.
Parameters
levelNameName of the level to load. Make sure it's available to all clients in the same room.
modeLoadSceneMode either single or additive
static void PhotonNetwork.NetworkStatisticsReset ( )
static

Resets the traffic stats and re-enables them.

static string PhotonNetwork.NetworkStatisticsToString ( )
static

Only available when NetworkStatisticsEnabled was used to gather some stats.

Returns
A string with vital networking statistics.
static void PhotonNetwork.OverrideBestCloudServer ( CloudRegionCode  region)
static

Overwrites the region that is used for ConnectToBestCloudServer(string gameVersion).

This will overwrite the result of pinging all cloud servers.
Use this to allow your users to save a manually selected region in the player preferences.
Note: You can also use PhotonNetwork.ConnectToRegion to (temporarily) connect to a specific region.

static bool PhotonNetwork.RaiseEvent ( byte  eventCode,
object  eventContent,
bool  sendReliable,
RaiseEventOptions  options 
)
static

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

To receive the events someone sends, register your handling method in PhotonNetwork.OnEventCall.

Example: private void OnEventHandler(byte eventCode, object content, int senderId) { Debug.Log("OnEventHandler"); }

PhotonNetwork.OnEventCall += this.OnEventHandler;

With the senderId, you can look up the PhotonPlayer who sent the event. It is best practice to assign a eventCode for each different type of content and action. You have to cast the content.

The eventContent is optional. To be able to send something, it 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 or classes some project defines are NOT supported! You can make your own class 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 PhotonPlayer.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.
sendReliableMakes sure this event reaches all players. It gets acknowledged, which requires bandwidth and it can't be skipped (might add lag in case of loss).
optionsAllows more complex usage of events. If null, RaiseEventOptions.Default will be used (which is fine).
Returns
False if event could not be sent
static bool PhotonNetwork.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 ReJoin(roomname) to return to a game. Common use case: Press the Lock Button on a iOS device and you get disconnected immediately.

static bool PhotonNetwork.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 OnPhotonJoinRoomFailed 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.ReJoin, this requires you to use unique IDs per player (the UserID).

Returns
False, if there is no known room or game server to return to. Then, this client does not attempt the ReconnectAndRejoin.
static void PhotonNetwork.RefreshCloudServerRating ( )
static

Pings all cloud servers again to find the one with best ping (currently).

static bool PhotonNetwork.ReJoinRoom ( string  roomName)
static

Can be used to return to a room after a disconnect and reconnect.

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 ReJoin(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. 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.

static void PhotonNetwork.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 PhotonNetwork.RemoveRPCs ( PhotonPlayer  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 PhotonPlayer'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 PhotonNetwork.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 PhotonNetwork.RemoveRPCsInGroup ( int  targetGroup)
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
targetGroupInterest group that gets all RPCs removed.
static void PhotonNetwork.SendOutgoingCommands ( )
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 PhotonNetwork.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/current/gameplay/interestgroups

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

Parameters
groupThe interest group to affect.
enabledSets if receiving from group to enabled (or not).
static void PhotonNetwork.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/current/gameplay/interestgroups

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

Parameters
disableGroupsThe interest groups to disable (or null).
enableGroupsThe interest groups to enable (or null).
static void PhotonNetwork.SetLevelPrefix ( short  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 = 32767
static bool PhotonNetwork.SetMasterClient ( PhotonPlayer  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 PhotonNetwork.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 PhotonNetwork.SetReceivingEnabled ( int  group,
bool  enabled 
)
static
static void PhotonNetwork.SetReceivingEnabled ( int[]  enableGroups,
int[]  disableGroups 
)
static
static void PhotonNetwork.SetSendingEnabled ( int  group,
bool  enabled 
)
static
static void PhotonNetwork.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 PhotonNetwork.SetSendingEnabled ( int[]  enableGroups,
int[]  disableGroups 
)
static
static void PhotonNetwork.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 void PhotonNetwork.SwitchToProtocol ( ConnectionProtocol  cp)
static

While offline, the network protocol can be switched (which affects the ports you can use to connect).

When you switch the protocol, make sure to also switch the port for the master server. Default ports are: TCP: 4530 UDP: 5055

This could look like this:
Connect(serverAddress, <udpport|tcpport>, appID, gameVersion)

Or when you use ConnectUsingSettings(), the PORT in the settings can be switched like so:
PhotonNetwork.PhotonServerSettings.ServerPort = 4530;

The current protocol can be read this way:
PhotonNetwork.networkingPeer.UsedProtocol

This does not work with the native socket plugin of PUN+ on mobile!

Parameters
cpNetwork protocol to use as low level connection. UDP is default. TCP is not available on all platforms (see remarks).
static void PhotonNetwork.UnAllocateViewID ( int  viewID)
static

Unregister a viewID (of manually instantiated and destroyed networked objects).

Parameters
viewIDA viewID manually allocated by this player.
static bool PhotonNetwork.WebRpc ( string  name,
object  parameters 
)
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/current/gameplay/web-extensions/webrpc The Parameters will be converted into JSon format, so make sure your parameters are compatible.

See PhotonNetworkingMessage.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

float PhotonNetwork.BackgroundTimeout = 60.0f
static

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 backgroung timeout is 60 seconds.

To handle the timeout, implement: OnDisconnectedFromPhoton(), 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).

A value below 0.1 seconds will disable this timeout (careful: connections can be kept indefinitely).

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'd expect on the platform you target! Check PhotonHandler.OnApplicationPause(bool pause), to see the implementation.

bool PhotonNetwork.InstantiateInRoomOnly = true
static

If true, Instantiate methods will check if you are in a room and fail if you are not.

Instantiating anything outside of a specific room is very likely to break things. Turn this off only if you know what you do.

PhotonLogLevel PhotonNetwork.logLevel = PhotonLogLevel.ErrorsOnly
static

Network log level. Controls how verbose PUN is.

readonly int PhotonNetwork.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.

int PhotonNetwork.maxConnections
static

Only used in Unity Networking. In PUN, set the number of players in PhotonNetwork.CreateRoom.

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

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

float PhotonNetwork.precisionForFloatSynchronization = 0.01f
static

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

float PhotonNetwork.precisionForQuaternionSynchronization = 1.0f
static

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

float PhotonNetwork.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.

Dictionary<string, GameObject> PhotonNetwork.PrefabCache = new Dictionary<string, GameObject>()
static

Keeps references to GameObjects for frequent instantiation (out of memory instead of loading the Resources).

You should be able to modify the cache anytime you like, except while Instantiate is used. Best do it only in the main-Thread.

HashSet<GameObject> PhotonNetwork.SendMonoMessageTargets
static

If not null, this is the (exclusive) list of GameObjects that get called by PUN SendMonoMessage().

For all callbacks defined in PhotonNetworkingMessage, PUN will use SendMonoMessage and call FindObjectsOfType() to find all scripts and GameObjects that might want a callback by PUN.

PUN callbacks are not very frequent (in-game, property updates are most frequent) but FindObjectsOfType is time consuming and with a large number of GameObjects, performance might suffer.

Optionally, SendMonoMessageTargets can be used to supply a list of target GameObjects. This skips the FindObjectsOfType() but any GameObject that needs callbacks will have to Add itself to this list.

If null, the default behaviour is to do a SendMessage on each GameObject with a MonoBehaviour.

Type PhotonNetwork.SendMonoMessageTargetType = typeof(MonoBehaviour)
static

Defines which classes can contain PUN Callback implementations.

This provides the option to optimize your runtime for speed.
The more specific this Type is, the fewer classes will be checked with reflection for callback methods.

bool PhotonNetwork.StartRpcsAsCoroutine = true
static

Can be used to skip starting RPCs as Coroutine, which can be a performance issue.

bool PhotonNetwork.UsePrefabCache = true
static

While enabled (true), Instantiate uses PhotonNetwork.PrefabCache to keep game objects in memory (improving instantiation of the same prefab).

Setting UsePrefabCache to false during runtime will not clear PrefabCache but will ignore it right away. You could clean and modify the cache yourself. Read its comments.

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

const string PhotonNetwork.versionPUN = "1.91"

Version number of PUN. Also used in GameVersion to separate client version from each other.

Property Documentation

AuthenticationValues PhotonNetwork.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 debugMsg). See: PhotonNetworkingMessage.OnCustomAuthenticationFailed

bool PhotonNetwork.autoCleanUpPlayerObjects
staticgetset

This setting defines per room, if network-instantiated GameObjects (with PhotonView) get cleaned up when the creator of it leaves.

This setting is done per room. It can't be changed in the room and it will override the settings of individual clients.

If room.AutoCleanUp is enabled in a room, the PUN clients will destroy a player's GameObjects on leave. This includes GameObjects manually instantiated (via RPCs, e.g.). When enabled, the server will clean RPCs, instantiated GameObjects and PhotonViews of the leaving player, too. and Players who join after someone left, won't get the events of that player anymore.

Under the hood, this setting is stored as a Custom Room Property. Enabled by default.

bool PhotonNetwork.autoJoinLobby
staticgetset

Set in PhotonServerSettings asset. Defines if the PhotonNetwork should join the "lobby" when connected to the Master server.

If this is false, OnConnectedToMaster() will be called when connection to the Master is available. OnJoinedLobby() will NOT be called if this is false.

Enabled by default.

The room listing will not become available. Rooms can be created and joined (randomly) without joining the lobby (and getting sent the room list).

bool PhotonNetwork.automaticallySyncScene
staticgetset

Defines if all clients in a room should load the same level as the Master Client (if that used PhotonNetwork.LoadLevel).

To synchronize the loaded level, the Master Client should use PhotonNetwork.LoadLevel. All clients will load the new scene when they get the update or when they join.

Internally, a Custom Room Property is set for the loaded scene. When a client reads that and is not in the same scene yet, it will immediately pause the Message Queue (PhotonNetwork.isMessageQueueRunning = false) and load. When the scene finished loading, PUN will automatically re-enable the Message Queue.

CloudRegionCode PhotonNetwork.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.

bool PhotonNetwork.connected
staticget

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

bool PhotonNetwork.connectedAndReady
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 PhotonNetwork.connecting
staticget

True when you called ConnectUsingSettings (or similar) until the low level connection to Photon gets established.

ConnectionState PhotonNetwork.connectionState
staticget

Simplified connection state

ClientState PhotonNetwork.connectionStateDetailed
staticget

Detailed connection state (ignorant of PUN, so it can be "disconnected" while switching servers).

In OfflineMode, this is ClientState.Joined (after create/join) or it is ConnectedToMaster in all other cases.

int PhotonNetwork.countOfPlayers
staticget

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

int PhotonNetwork.countOfPlayersInRooms
staticget

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

int PhotonNetwork.countOfPlayersOnMaster
staticget

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

int PhotonNetwork.countOfRooms
staticget

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

While inside the lobby you can also check the count of listed rooms as: PhotonNetwork.GetRoomList().Length. Since PUN v1.25 this is only based on the statistic event Photon sends (counting all rooms).

bool PhotonNetwork.CrcCheckEnabled
staticgetset

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

bool PhotonNetwork.EnableLobbyStatistics
staticgetset

Set in PhotonServerSettings asset. Enable to get a list of active lobbies from the Master Server.

Lobby Statistics can be useful if a game uses multiple lobbies and you want to show activity of each to players.

This value is stored in PhotonServerSettings.

PhotonNetwork.LobbyStatistics is updated when you connect to the Master Server. There is also a callback PunBehaviour.

List<FriendInfo> PhotonNetwork.Friends
staticgetset

Read-only list of friends, their online status and the room they are in. Null until initialized by a FindFriends call.

Do not modify this list! It is internally handled by FindFriends and only available to read the values. The value of FriendListAge tells you how old the data is in milliseconds.

Don't get this list more often than useful (> 10 seconds). In best case, keep the list you fetch really short. You could (e.g.) get the full list only once, then request a few updates only for friends who are online. After a while (e.g. 1 minute), you can get the full list again (to update online states).

int PhotonNetwork.FriendsListAge
staticget

Age of friend list info (in milliseconds). It's 0 until a friend list is fetched.

string PhotonNetwork.gameVersion
staticgetset

Version string for your this build. Can be used to separate incompatible clients. Sent during connect.

This is only sent when you connect so that is also the place you set it usually (e.g. in ConnectUsingSettings).

bool PhotonNetwork.inRoom
staticget

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

Many actions can only be executed in a room, like Instantiate or Leave, etc. You can join a room in offline mode, too.

bool PhotonNetwork.insideLobby
staticget

True while this client is in a lobby.

Implement IPunCallbacks.OnReceivedRoomListUpdate() 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 PhotonNetwork.isMasterClient
staticget

Are we the master client?

bool PhotonNetwork.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.

bool PhotonNetwork.isNonMasterClientInRoom
staticget

True if we are in a room (client) and NOT the room's masterclient

TypedLobby PhotonNetwork.lobby
staticgetset

The lobby that will be used when PUN joins a lobby or creates a game.

The default lobby uses an empty string as name. PUN will enter a lobby on the Master Server if autoJoinLobby is set to true. So when you connect or leave a room, PUN automatically gets you into a lobby again.

Check PhotonNetwork.insideLobby if the client is in a lobby. (Master Server And Lobby)

List<TypedLobbyInfo> PhotonNetwork.LobbyStatistics
staticgetset

If turned on, the Master Server will provide information about active lobbies for this application.

Lobby Statistics can be useful if a game uses multiple lobbies and you want to show activity of each to players. Per lobby, you get: name, type, room- and player-count.

PhotonNetwork.LobbyStatistics is updated when you connect to the Master Server. There is also a callback PunBehaviour.OnLobbyStatisticsUpdate, which you should implement to update your UI (e.g.).

Lobby Statistics are not turned on by default. Enable them in the PhotonServerSettings file of the project.

PhotonPlayer PhotonNetwork.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 PhotonNetwork.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.

bool PhotonNetwork.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

bool PhotonNetwork.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

PhotonPlayer [] PhotonNetwork.otherPlayers
staticget

The list of players in the current room, excluding the local player.

This list is only valid, while the client is in a room. It automatically gets updated when someone joins or leaves.

This can be used to list all other players in a room. Each player's PhotonPlayer.customProperties are accessible (set and synchronized via PhotonPlayer.SetCustomProperties).

You can use a PhotonPlayer.TagObject to store an arbitrary object for reference. That is not synchronized via the network.

int PhotonNetwork.PacketLossByCrcCheck
staticget

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

PhotonPlayer PhotonNetwork.player
staticget

The local PhotonPlayer. Always available and represents this player. CustomProperties can be set before entering a room and will be synced as well.

PhotonPlayer [] PhotonNetwork.playerList
staticget

The list of players in the current room, including the local player.

This list is only valid, while the client is in a room. It automatically gets updated when someone joins or leaves.

This can be used to list all players in a room. Each player's PhotonPlayer.customProperties are accessible (set and synchronized via PhotonPlayer.SetCustomProperties).

You can use a PhotonPlayer.TagObject to store an arbitrary object for reference. That is not synchronized via the network.

string PhotonNetwork.playerName
staticgetset

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

The playerName 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: PhotonPlayer.NickName.
PhotonNetwork.otherPlayers is a list of other players - each contains the playerName the remote player set.

IPunPrefabPool PhotonNetwork.PrefabPool
staticgetset

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

To use a GameObject pool, implement IPunPrefabPool and assign it here. Prefabs are identified by name.

int PhotonNetwork.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 PhotonNetwork.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.

Room PhotonNetwork.room
staticget

Get the room we're currently in. Null if we aren't in any room.

int PhotonNetwork.sendRate
staticgetset

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

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 PhotonNetwork.sendRateOnSerialize
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 PhotonNetwork.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 PhotonNetwork.ServerAddress
staticget

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

int PhotonNetwork.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 PhotonNetwork.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!

int PhotonNetwork.unreliableCommandsLimit
staticgetset

Used once per dispatch to limit unreliable commands per channel (so after a pause, many channels can still cause a lot of unreliable commands)

bool PhotonNetwork.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.

Event Documentation

EventCallback PhotonNetwork.OnEventCall
static

Register your RaiseEvent handling methods here by using "+=".

Any eventCode < 200 will be forwarded to your delegate(s).

RaiseEvent