Best









How do I use Best
Below are practical examples compiled from projects for learning and reference purposes

Featured Snippets


File name: PhotonEditor.cs Copy
215     static PhotonEditor()
216     {
217         EditorApplication.projectWindowChanged += EditorUpdate;
218         EditorApplication.hierarchyWindowChanged += EditorUpdate;
219         EditorApplication.playmodeStateChanged += PlaymodeStateChanged;
220         EditorApplication.update += OnUpdate;
221
222         WizardIcon = AssetDatabase.LoadAssetAtPath("Assets/Photon Unity Networking/photoncloud-icon.png", typeof(Texture2D)) as Texture2D;
223
224         // to be used in toolbar, the enum needs conversion to string[] being done here, once.
225         Array enumValues = Enum.GetValues(typeof(CloudRegionCode));
226         CloudServerRegionNames = new string[enumValues.Length];
227         for (int i = 0; i < CloudServerRegionNames.Length; i++)
228         {
229             CloudServerRegionNames[i] = enumValues.GetValue(i).ToString();
230             if (CloudServerRegionNames[i].Equals("none"))
231             {
232                 CloudServerRegionNames[i] = PhotonEditor.CurrentLang.BestRegionLabel;
233             }
234         }
235
236         // detect optional packages
237         PhotonEditor.CheckPunPlus();
238
239     }
File name: PhotonEditor.cs Copy
294     protected void InitPhotonSetupWindow()
295     {
296         this.minSize = MinSize;
297
298         this.SwitchMenuState(GUIState.Setup);
299         this.ReApplySettingsToWindow();
300
301         switch (PhotonEditor.Current.HostType)
302         {
303             case ServerSettings.HostingOption.PhotonCloud:
304             case ServerSettings.HostingOption.BestRegion:
305                 this.photonSetupState = PhotonSetupStates.SetupPhotonCloud;
306                 break;
307             case ServerSettings.HostingOption.SelfHosted:
308                 this.photonSetupState = PhotonSetupStates.SetupSelfHosted;
309                 break;
310             case ServerSettings.HostingOption.NotSet:
311             default:
312                 this.photonSetupState = PhotonSetupStates.RegisterForPhotonCloud;
313                 break;
314         }
315     }
File name: PhotonEditor.cs Copy
649     protected virtual void OnGuiSetupCloudAppId()
650     {
651         GUILayout.Label(CurrentLang.AppIdLabel);
652
653         GUILayout.BeginHorizontal();
654         this.cloudAppId = EditorGUILayout.TextField(this.cloudAppId);
655
656         open = GUILayout.Toggle(open, PhotonGUI.HelpIcon, GUIStyle.none, GUILayout.ExpandWidth(false));
657
658         GUILayout.EndHorizontal();
659
660         if (open) GUILayout.Label(CurrentLang.AppIdInfoLabel);
661
662
663
664         EditorGUILayout.Separator();
665
666         GUILayout.Label(CurrentLang.CloudRegionLabel);
667
668         GUILayout.BeginHorizontal();
669         int toolbarValue = GUILayout.Toolbar((int)selectedRegion, CloudServerRegionNames); // the enum CloudRegionCode is converted into a string[] in init (toolbar can't use enum)
670         helpRegion = GUILayout.Toggle( helpRegion, PhotonGUI.HelpIcon, GUIStyle.none, GUILayout.ExpandWidth( false ) );
671         GUILayout.EndHorizontal();
672
673
674         if (helpRegion) GUILayout.Label(CurrentLang.RegionalServersInfo);
675         PhotonEditor.selectedRegion = (CloudRegionCode)toolbarValue;
676
677         EditorGUILayout.Separator();
678
679         GUILayout.BeginHorizontal();
680         if (GUILayout.Button(CurrentLang.CancelButton))
681         {
682             GUIUtility.keyboardControl = 0;
683             this.ReApplySettingsToWindow();
684         }
685
686
687
688         if (GUILayout.Button(CurrentLang.SaveButton))
689         {
690             GUIUtility.keyboardControl = 0;
691             this.cloudAppId = this.cloudAppId.Trim();
692             PhotonEditor.Current.UseCloud(this.cloudAppId);
693
694             PhotonEditor.Current.PreferredRegion = PhotonEditor.selectedRegion;
695             PhotonEditor.Current.HostType = (PhotonEditor.Current.PreferredRegion == CloudRegionCode.none)
696                                                 ? ServerSettings.HostingOption.BestRegion
697                                                 : ServerSettings.HostingOption.PhotonCloud;
698             PhotonEditor.Save();
699
700             Inspect();
701             EditorUtility.DisplayDialog(CurrentLang.SettingsSavedTitle, CurrentLang.SettingsSavedMessage, CurrentLang.OkButton);
702         }
703
704         GUILayout.EndHorizontal();
705
706
707
708         GUILayout.Space(20);
709
710         GUILayout.Label(CurrentLang.SetupOwnServerLabel);
711
712         if (GUILayout.Button(CurrentLang.SelfHostSettingsButton))
713         {
714             //this.photonAddress = ServerSettings.DefaultServerAddress;
715             //this.photonPort = ServerSettings.DefaultMasterPort;
716             this.photonSetupState = PhotonSetupStates.SetupSelfHosted;
717         }
718
719         EditorGUILayout.Separator();
720         GUILayout.Label(CurrentLang.OwnHostCloudCompareLabel);
721         if (GUILayout.Button(CurrentLang.ComparisonPageButton))
722         {
723             Application.OpenURL(UrlCompare);
724         }
725     }
File name: ServerSettingsInspector.cs Copy
17     public override void OnInspectorGUI()
18     {
19         ServerSettings settings = (ServerSettings)this.target;
20
21         #if UNITY_3_5
22         EditorGUIUtility.LookLikeInspector();
23         #endif
24
25
26         settings.HostType = (ServerSettings.HostingOption)EditorGUILayout.EnumPopup("Hosting", settings.HostType);
27         EditorGUI.indentLevel = 1;
28
29         switch (settings.HostType)
30         {
31             case ServerSettings.HostingOption.BestRegion:
32             case ServerSettings.HostingOption.PhotonCloud:
33                 if (settings.HostType == ServerSettings.HostingOption.PhotonCloud)
34                     settings.PreferredRegion = (CloudRegionCode)EditorGUILayout.EnumPopup("Region", settings.PreferredRegion);
35                 settings.AppID = EditorGUILayout.TextField("AppId", settings.AppID);
36                 settings.Protocol = (ConnectionProtocol)EditorGUILayout.EnumPopup("Protocol", settings.Protocol);
37
38                 if (string.IsNullOrEmpty(settings.AppID) || settings.AppID.Equals("master"))
39                 {
40                     EditorGUILayout.HelpBox("The Photon Cloud needs an AppId (GUID) set.\nYou can find it online in your Dashboard.", MessageType.Warning);
41                 }
42                 break;
43
44             case ServerSettings.HostingOption.SelfHosted:
45                 bool hidePort = false;
46                 if (settings.Protocol == ConnectionProtocol.Udp && (settings.ServerPort == 4530 || settings.ServerPort == 0))
47                 {
48                     settings.ServerPort = 5055;
49                 }
50                 else if (settings.Protocol == ConnectionProtocol.Tcp && (settings.ServerPort == 5055 || settings.ServerPort == 0))
51                 {
52                     settings.ServerPort = 4530;
53                 }
54                 #if RHTTP
55                 if (settings.Protocol == ConnectionProtocol.RHttp)
56                 {
57                     settings.ServerPort = 0;
58                     hidePort = true;
59                 }
60                 #endif
61                 settings.ServerAddress = EditorGUILayout.TextField("Server Address", settings.ServerAddress);
62                 settings.ServerAddress = settings.ServerAddress.Trim();
63                 if (!hidePort)
64                 {
65                     settings.ServerPort = EditorGUILayout.IntField("Server Port", settings.ServerPort);
66                 }
67                 settings.Protocol = (ConnectionProtocol)EditorGUILayout.EnumPopup("Protocol", settings.Protocol);
68                 settings.AppID = EditorGUILayout.TextField("AppId", settings.AppID);
69                 break;
70
71             case ServerSettings.HostingOption.OfflineMode:
72                 EditorGUI.indentLevel = 0;
73                 EditorGUILayout.HelpBox("In 'Offline Mode', the client does not communicate with a server.\nAll settings are hidden currently.", MessageType.Info);
74                 break;
75
76             case ServerSettings.HostingOption.NotSet:
77                 EditorGUI.indentLevel = 0;
78                 EditorGUILayout.HelpBox("Hosting is 'Not Set'.\nConnectUsingSettings() will not be able to connect.\nSelect another option or run the PUN Wizard.", MessageType.Info);
79                 break;
80
81             default:
82                 DrawDefaultInspector();
83                 break;
84         }
85
86         if (PhotonEditor.CheckPunPlus())
87         {
88             settings.Protocol = ConnectionProtocol.Udp;
89             EditorGUILayout.HelpBox("You seem to use PUN+.\nPUN+ only supports reliable UDP so the protocol is locked.", MessageType.Info);
90         }
91
92         settings.AppID = settings.AppID.Trim();
93
94         EditorGUI.indentLevel = 0;
95         SerializedObject sObj = new SerializedObject(this.target);
96         SerializedProperty sRpcs = sObj.FindProperty("RpcList");
97         EditorGUILayout.PropertyField(sRpcs, true);
98         sObj.ApplyModifiedProperties();
99
100         GUILayout.BeginHorizontal();
101         GUILayout.Space(20);
102         if (GUILayout.Button("Refresh RPCs"))
103         {
104             PhotonEditor.UpdateRpcList();
105             Repaint();
106         }
107         if (GUILayout.Button("Clear RPCs"))
108         {
109             PhotonEditor.ClearRpcList();
110         }
111         if (GUILayout.Button("Log HashCode"))
112         {
113             Debug.Log("RPC-List HashCode: " + RpcListHashCode() + ". Make sure clients that send each other RPCs have the same RPC-List.");
114         }
115         GUILayout.Space(20);
116         GUILayout.EndHorizontal();
117
118         //SerializedProperty sp = serializedObject.FindProperty("RpcList");
119         //EditorGUILayout.PropertyField(sp, true);
120
121         if (GUI.changed)
122         {
123             EditorUtility.SetDirty(target);
124         }
125     }
File name: NetworkingPeer.cs Copy
1016     public void OnOperationResponse(OperationResponse operationResponse)
1017     {
1018         if (PhotonNetwork.networkingPeer.State == global::PeerState.Disconnecting)
1019         {
1020             if (PhotonNetwork.logLevel >= PhotonLogLevel.Informational)
1021             {
1022                 Debug.Log("OperationResponse ignored while disconnecting. Code: " + operationResponse.OperationCode);
1023             }
1024             return;
1025         }
1026
1027         // extra logging for error debugging (helping developers with a bit of automated analysis)
1028         if (operationResponse.ReturnCode == 0)
1029         {
1030             if (PhotonNetwork.logLevel >= PhotonLogLevel.Informational)
1031                 Debug.Log(operationResponse.ToString());
1032         }
1033         else
1034         {
1035             if (operationResponse.ReturnCode == ErrorCode.OperationNotAllowedInCurrentState)
1036             {
1037                 Debug.LogError("Operation " + operationResponse.OperationCode + " could not be executed (yet). Wait for state JoinedLobby or ConnectedToMaster and their callbacks before calling operations. WebRPCs need a server-side configuration. Enum OperationCode helps identify the operation.");
1038             }
1039             else if (operationResponse.ReturnCode == ErrorCode.WebHookCallFailed)
1040             {
1041                 Debug.LogError("Operation " + operationResponse.OperationCode + " failed in a server-side plugin. Check the configuration in the Dashboard. Message from server-plugin: " + operationResponse.DebugMessage);
1042             }
1043             else if (PhotonNetwork.logLevel >= PhotonLogLevel.Informational)
1044             {
1045                 Debug.LogError("Operation failed: " + operationResponse.ToStringFull() + " Server: " + this.server);
1046             }
1047         }
1048
1049         // use the "secret" or "token" whenever we get it. doesn't really matter if it's in AuthResponse.
1050         if (operationResponse.Parameters.ContainsKey(ParameterCode.Secret))
1051         {
1052             if (this.CustomAuthenticationValues == null)
1053             {
1054                 this.CustomAuthenticationValues = new AuthenticationValues();
1055                 // this.DebugReturn(DebugLevel.ERROR, "Server returned secret. Created CustomAuthenticationValues.");
1056             }
1057
1058             this.CustomAuthenticationValues.Secret = operationResponse[ParameterCode.Secret] as string;
1059         }
1060
1061         switch (operationResponse.OperationCode)
1062         {
1063             case OperationCode.Authenticate:
1064                 {
1065                     // PeerState oldState = this.State;
1066
1067                     if (operationResponse.ReturnCode != 0)
1068                     {
1069                         if (operationResponse.ReturnCode == ErrorCode.InvalidOperationCode)
1070                         {
1071                             Debug.LogError(string.Format("If you host Photon yourself, make sure to start the 'Instance LoadBalancing' "+ this.ServerAddress));
1072                         }
1073                         else if (operationResponse.ReturnCode == ErrorCode.InvalidAuthentication)
1074                         {
1075                             Debug.LogError(string.Format("The appId this client sent is unknown on the server (Cloud). Check settings. If using the Cloud, check account."));
1076                             SendMonoMessage(PhotonNetworkingMessage.OnFailedToConnectToPhoton, DisconnectCause.InvalidAuthentication);
1077                         }
1078                         else if (operationResponse.ReturnCode == ErrorCode.CustomAuthenticationFailed)
1079                         {
1080                             Debug.LogError(string.Format("Custom Authentication failed (either due to user-input or configuration or AuthParameter string format). Calling: OnCustomAuthenticationFailed()"));
1081                             SendMonoMessage(PhotonNetworkingMessage.OnCustomAuthenticationFailed, operationResponse.DebugMessage);
1082                         }
1083                         else
1084                         {
1085                             Debug.LogError(string.Format("Authentication failed: '{0}' Code: {1}", operationResponse.DebugMessage, operationResponse.ReturnCode));
1086                         }
1087
1088                         this.State = global::PeerState.Disconnecting;
1089                         this.Disconnect();
1090
1091                         if (operationResponse.ReturnCode == ErrorCode.MaxCcuReached)
1092                         {
1093                             if (PhotonNetwork.logLevel >= PhotonLogLevel.Informational)
1094                                 Debug.LogWarning(string.Format("Currently, the limit of users is reached for this title. Try again later. Disconnecting"));
1095                             SendMonoMessage(PhotonNetworkingMessage.OnPhotonMaxCccuReached);
1096                             SendMonoMessage(PhotonNetworkingMessage.OnConnectionFail, DisconnectCause.MaxCcuReached);
1097                         }
1098                         else if (operationResponse.ReturnCode == ErrorCode.InvalidRegion)
1099                         {
1100                             if (PhotonNetwork.logLevel >= PhotonLogLevel.Informational)
1101                                 Debug.LogError(string.Format("The used master server address is not available with the subscription currently used. Got to Photon Cloud Dashboard or change URL. Disconnecting."));
1102                             SendMonoMessage(PhotonNetworkingMessage.OnConnectionFail, DisconnectCause.InvalidRegion);
1103                         }
1104                         else if (operationResponse.ReturnCode == ErrorCode.AuthenticationTicketExpired)
1105                         {
1106                             if (PhotonNetwork.logLevel >= PhotonLogLevel.Informational)
1107                                 Debug.LogError(string.Format("The authentication ticket expired. You need to connect (and authenticate) again. Disconnecting."));
1108                             SendMonoMessage(PhotonNetworkingMessage.OnConnectionFail, DisconnectCause.AuthenticationTicketExpired);
1109                         }
1110                         break;
1111                     }
1112                     else
1113                     {
1114                         if (this.server == ServerConnection.NameServer)
1115                         {
1116                             // on the NameServer, authenticate returns the MasterServer address for a region and we hop off to there
1117                             this.MasterServerAddress = operationResponse[ParameterCode.Address] as string;
1118                             this.DisconnectToReconnect();
1119                         }
1120                         else if (this.server == ServerConnection.MasterServer)
1121                         {
1122                             if (PhotonNetwork.autoJoinLobby)
1123                             {
1124                                 this.State = global::PeerState.Authenticated;
1125                                 this.OpJoinLobby(this.lobby);
1126                             }
1127                             else
1128                             {
1129                                 this.State = global::PeerState.ConnectedToMaster;
1130                                 NetworkingPeer.SendMonoMessage(PhotonNetworkingMessage.OnConnectedToMaster);
1131                             }
1132                         }
1133                         else if (this.server == ServerConnection.GameServer)
1134                         {
1135                             this.State = global::PeerState.Joining;
1136
1137                             if (this.mLastJoinType == JoinType.JoinGame || this.mLastJoinType == JoinType.JoinRandomGame || this.mLastJoinType == JoinType.JoinOrCreateOnDemand)
1138                             {
1139                                 // if we just "join" the game, do so. if we wanted to "create the room on demand", we have to send this to the game server as well.
1140                                 this.OpJoinRoom(this.mRoomToGetInto.name, this.mRoomOptionsForCreate, this.mRoomToEnterLobby, this.mLastJoinType == JoinType.JoinOrCreateOnDemand);
1141                             }
1142                             else if (this.mLastJoinType == JoinType.CreateGame)
1143                             {
1144                                 // on the game server, we have to apply the room properties that were chosen for creation of the room, so we use this.mRoomToGetInto
1145                                 this.OpCreateGame(this.mRoomToGetInto.name, this.mRoomOptionsForCreate, this.mRoomToEnterLobby);
1146                             }
1147
1148                             break;
1149                         }
1150                     }
1151                     break;
1152                 }
1153
1154             case OperationCode.GetRegions:
1155                 // Debug.Log("GetRegions returned: " + operationResponse.ToStringFull());
1156
1157                 if (operationResponse.ReturnCode == ErrorCode.InvalidAuthentication)
1158                 {
1159                     Debug.LogError(string.Format("The appId this client sent is unknown on the server (Cloud). Check settings. If using the Cloud, check account."));
1160                     SendMonoMessage(PhotonNetworkingMessage.OnFailedToConnectToPhoton, DisconnectCause.InvalidAuthentication);
1161
1162                     this.State = global::PeerState.Disconnecting;
1163                     this.Disconnect();
1164                     return;
1165                 }
1166
1167                 string[] regions = operationResponse[ParameterCode.Region] as string[];
1168                 string[] servers = operationResponse[ParameterCode.Address] as string[];
1169
1170                 if (regions == null || servers == null || regions.Length != servers.Length)
1171                 {
1172                     Debug.LogError("The region arrays from Name Server are not ok. Must be non-null and same length.");
1173                     break;
1174                 }
1175
1176                 this.AvailableRegions = new List(regions.Length);
1177                 for (int i = 0; i < regions.Length; i++)
1178                 {
1179                     string regionCodeString = regions[i];
1180                     if (string.IsNullOrEmpty(regionCodeString))
1181                     {
1182                         continue;
1183                     }
1184                     regionCodeString = regionCodeString.ToLower();
1185
1186                     CloudRegionCode code = Region.Parse(regionCodeString);
1187                     this.AvailableRegions.Add(new Region() { Code = code, HostAndPort = servers[i] });
1188                 }
1189
1190                 // PUN assumes you fetch the name-server's list of regions to ping them
1191                 if (PhotonNetwork.PhotonServerSettings.HostType == ServerSettings.HostingOption.BestRegion)
1192                 {
1193                     PhotonHandler.PingAvailableRegionsAndConnectToBest();
1194                 }
1195                 break;
1196
1197             case OperationCode.CreateGame:
1198                 {
1199                     if (this.server == ServerConnection.GameServer)
1200                     {
1201                         this.GameEnteredOnGameServer(operationResponse);
1202                     }
1203                     else
1204                     {
1205                         if (operationResponse.ReturnCode != 0)
1206                         {
1207                             if (PhotonNetwork.logLevel >= PhotonLogLevel.Informational)
1208                                 Debug.LogWarning(string.Format("CreateRoom failed, client stays on masterserver: {0}.", operationResponse.ToStringFull()));
1209
1210                             SendMonoMessage(PhotonNetworkingMessage.OnPhotonCreateRoomFailed);
1211                             break;
1212                         }
1213
1214                         string gameID = (string) operationResponse[ParameterCode.RoomName];
1215                         if (!string.IsNullOrEmpty(gameID))
1216                         {
1217                             // is only sent by the server's response, if it has not been
1218                             // sent with the client's request before!
1219                             this.mRoomToGetInto.name = gameID;
1220                         }
1221
1222                         this.mGameserver = (string)operationResponse[ParameterCode.Address];
1223                         this.DisconnectToReconnect();
1224                     }
1225
1226                     break;
1227                 }
1228
1229             case OperationCode.JoinGame:
1230                 {
1231                     if (this.server != ServerConnection.GameServer)
1232                     {
1233                         if (operationResponse.ReturnCode != 0)
1234                         {
1235                             if (PhotonNetwork.logLevel >= PhotonLogLevel.Informational)
1236                                 Debug.Log(string.Format("JoinRoom failed (room maybe closed by now). Client stays on masterserver: {0}. State: {1}", operationResponse.ToStringFull(), this.State));
1237
1238                             SendMonoMessage(PhotonNetworkingMessage.OnPhotonJoinRoomFailed);
1239                             break;
1240                         }
1241
1242                         this.mGameserver = (string)operationResponse[ParameterCode.Address];
1243                         this.DisconnectToReconnect();
1244                     }
1245                     else
1246                     {
1247                         this.GameEnteredOnGameServer(operationResponse);
1248                     }
1249
1250                     break;
1251                 }
1252
1253             case OperationCode.JoinRandomGame:
1254                 {
1255                     // happens only on master. on gameserver, this is a regular join (we don't need to find a random game again)
1256                     // the operation OpJoinRandom either fails (with returncode 8) or returns game-to-join information
1257                     if (operationResponse.ReturnCode != 0)
1258                     {
1259                         if (operationResponse.ReturnCode == ErrorCode.NoRandomMatchFound)
1260                         {
1261                             if (PhotonNetwork.logLevel >= PhotonLogLevel.Full)
1262                                 Debug.Log("JoinRandom failed: No open game. Calling: OnPhotonRandomJoinFailed() and staying on master server.");
1263                         }
1264                         else if (PhotonNetwork.logLevel >= PhotonLogLevel.Informational)
1265                         {
1266                             Debug.LogWarning(string.Format("JoinRandom failed: {0}.", operationResponse.ToStringFull()));
1267                         }
1268
1269                         SendMonoMessage(PhotonNetworkingMessage.OnPhotonRandomJoinFailed, operationResponse.ReturnCode, operationResponse.DebugMessage);
1270                         break;
1271                     }
1272
1273                     string roomName = (string)operationResponse[ParameterCode.RoomName];
1274                     this.mRoomToGetInto.name = roomName;
1275                     this.mGameserver = (string)operationResponse[ParameterCode.Address];
1276                     this.DisconnectToReconnect();
1277                     break;
1278                 }
1279
1280             case OperationCode.JoinLobby:
1281                 this.State = global::PeerState.JoinedLobby;
1282                 this.insideLobby = true;
1283                 SendMonoMessage(PhotonNetworkingMessage.OnJoinedLobby);
1284
1285                 // this.mListener.joinLobbyReturn();
1286                 break;
1287             case OperationCode.LeaveLobby:
1288                 this.State = global::PeerState.Authenticated;
1289                 this.LeftLobbyCleanup(); // will set insideLobby = false
1290                 break;
1291
1292             case OperationCode.Leave:
1293                 this.DisconnectToReconnect();
1294                 break;
1295
1296             case OperationCode.SetProperties:
1297                 // this.mListener.setPropertiesReturn(returnCode, debugMsg);
1298                 break;
1299
1300             case OperationCode.GetProperties:
1301                 {
1302                     Hashtable actorProperties = (Hashtable)operationResponse[ParameterCode.PlayerProperties];
1303                     Hashtable gameProperties = (Hashtable)operationResponse[ParameterCode.GameProperties];
1304                     this.ReadoutProperties(gameProperties, actorProperties, 0);
1305
1306                     // RemoveByteTypedPropertyKeys(actorProperties, false);
1307                     // RemoveByteTypedPropertyKeys(gameProperties, false);
1308                     // this.mListener.getPropertiesReturn(gameProperties, actorProperties, returnCode, debugMsg);
1309                     break;
1310                 }
1311
1312             case OperationCode.RaiseEvent:
1313                 // this usually doesn't give us a result. only if the caching is affected the server will send one.
1314                 break;
1315
1316             case OperationCode.FindFriends:
1317                 bool[] onlineList = operationResponse[ParameterCode.FindFriendsResponseOnlineList] as bool[];
1318                 string[] roomList = operationResponse[ParameterCode.FindFriendsResponseRoomIdList] as string[];
1319
1320                 if (onlineList != null && roomList != null && this.friendListRequested != null && onlineList.Length == this.friendListRequested.Length)
1321                 {
1322                     List friendList = new List(this.friendListRequested.Length);
1323                     for (int index = 0; index < this.friendListRequested.Length; index++)
1324                     {
1325                         FriendInfo friend = new FriendInfo();
1326                         friend.Name = this.friendListRequested[index];
1327                         friend.Room = roomList[index];
1328                         friend.IsOnline = onlineList[index];
1329                         friendList.Insert(index, friend);
1330                     }
1331                     PhotonNetwork.Friends = friendList;
1332                 }
1333                 else
1334                 {
1335                     // any of the lists is null and shouldn't. print a error
1336                     Debug.LogError("FindFriends failed to apply the result, as a required value wasn't provided or the friend list length differed from result.");
1337                 }
1338
1339                 this.friendListRequested = null;
1340                 this.isFetchingFriends = false;
1341                 this.friendListTimestamp = Environment.TickCount;
1342                 if (this.friendListTimestamp == 0)
1343                 {
1344                     this.friendListTimestamp = 1; // makes sure the timestamp is not accidentally 0
1345                 }
1346
1347                 SendMonoMessage(PhotonNetworkingMessage.OnUpdatedFriendList);
1348                 break;
1349
1350             case OperationCode.WebRpc:
1351                 SendMonoMessage(PhotonNetworkingMessage.OnWebRpcResponse, operationResponse);
1352                 break;
1353
1354             default:
1355                 Debug.LogWarning(string.Format("OperationResponse unhandled: {0}", operationResponse.ToString()));
1356                 break;
1357         }
1358
1359         this.externalListener.OnOperationResponse(operationResponse);
1360     }
File name: PhotonHandler.cs Copy
226     internal protected static void PingAvailableRegionsAndConnectToBest()
227     {
228         SP.StartCoroutine(SP.PingAvailableRegionsCoroutine(true));
229     }
File name: PhotonHandler.cs Copy
232     internal IEnumerator PingAvailableRegionsCoroutine(bool connectToBest)
233     {
234         BestRegionCodeCurrently = CloudRegionCode.none;
235         while (PhotonNetwork.networkingPeer.AvailableRegions == null)
236         {
237             if (PhotonNetwork.connectionStateDetailed != PeerState.ConnectingToNameServer && PhotonNetwork.connectionStateDetailed != PeerState.ConnectedToNameServer)
238             {
239                 Debug.LogError("Call ConnectToNameServer to ping available regions.");
240                 yield break; // break if we don't connect to the nameserver at all
241             }
242
243             Debug.Log("Waiting for AvailableRegions. State: " + PhotonNetwork.connectionStateDetailed + " Server: " + PhotonNetwork.Server + " PhotonNetwork.networkingPeer.AvailableRegions " + (PhotonNetwork.networkingPeer.AvailableRegions != null));
244             yield return new WaitForSeconds(0.25f); // wait until pinging finished (offline mode won't ping)
245         }
246
247         if (PhotonNetwork.networkingPeer.AvailableRegions == null || PhotonNetwork.networkingPeer.AvailableRegions.Count == 0)
248         {
249             Debug.LogError("No regions available. Are you sure your appid is valid and setup?");
250             yield break; // break if we don't get regions at all
251         }
252
253         //#if !UNITY_EDITOR && (UNITY_ANDROID || UNITY_IPHONE)
254         //#pragma warning disable 0162 // the library variant defines if we should use PUN's SocketUdp variant (at all)
255         //if (PhotonPeer.NoSocket)
256         //{
257         // if (PhotonNetwork.logLevel >= PhotonLogLevel.Informational)
258         // {
259         // Debug.Log("PUN disconnects to re-use native sockets for pining servers and to find the best.");
260         // }
261         // PhotonNetwork.Disconnect();
262         //}
263         //#pragma warning restore 0162
264         //#endif
265
266         PhotonPingManager pingManager = new PhotonPingManager();
267         foreach (Region region in PhotonNetwork.networkingPeer.AvailableRegions)
268         {
269             SP.StartCoroutine(pingManager.PingSocket(region));
270         }
271
272         while (!pingManager.Done)
273         {
274             yield return new WaitForSeconds(0.1f); // wait until pinging finished (offline mode won't ping)
275         }
276
277
278         Region best = pingManager.BestRegion;
279         PhotonHandler.BestRegionCodeCurrently = best.Code;
280         PhotonHandler.BestRegionCodeInPreferences = best.Code;
281
282         Debug.Log("Found best region: " + best.Code + " ping: " + best.Ping + ". Calling ConnectToRegionMaster() is: " + connectToBest);
283
284
285         if (connectToBest)
286         {
287             PhotonNetwork.networkingPeer.ConnectToRegionMaster(best.Code);
288         }
289     }
File name: PhotonNetwork.cs Copy
1109     /// - Invalid AppId (calls: OnFailedToConnectToPhoton(). check exact AppId value)
1110     /// - Network issues (calls: OnFailedToConnectToPhoton())
1111     /// - Invalid region (calls: OnConnectionFail() with DisconnectCause.InvalidRegion)
1112     /// - Subscription CCU limit reached (calls: OnConnectionFail() with DisconnectCause.MaxCcuReached. also calls: OnPhotonMaxCccuReached())
1118     public static bool ConnectUsingSettings(string gameVersion)
1119     {
1120         if (PhotonServerSettings == null)
1121         {
1122             Debug.LogError("Can't connect: Loading settings failed. ServerSettings asset must be in any 'Resources' folder as: " + serverSettingsAssetFile);
1123             return false;
1124         }
1125
1126         SwitchToProtocol(PhotonServerSettings.Protocol);
1127         networkingPeer.SetApp(PhotonServerSettings.AppID, gameVersion);
1128
1129         if (PhotonServerSettings.HostType == ServerSettings.HostingOption.OfflineMode)
1130         {
1131             offlineMode = true;
1132             return true;
1133         }
1134
1135         if (offlineMode)
1136         {
1137             // someone can set offlineMode in code and then call ConnectUsingSettings() with non-offline settings. Warning for that case:
1138             Debug.LogWarning("ConnectUsingSettings() disabled the offline mode. No longer offline.");
1139         }
1140
1141         offlineMode = false; // Cleanup offline mode
1142         isMessageQueueRunning = true;
1143         networkingPeer.IsInitialConnect = true;
1144
1145         if (PhotonServerSettings.HostType == ServerSettings.HostingOption.SelfHosted)
1146         {
1147             networkingPeer.IsUsingNameServer = false;
1148             networkingPeer.MasterServerAddress = (PhotonServerSettings.ServerPort == 0) ? PhotonServerSettings.ServerAddress : PhotonServerSettings.ServerAddress + ":" + PhotonServerSettings.ServerPort;
1149
1150             return networkingPeer.Connect(networkingPeer.MasterServerAddress, ServerConnection.MasterServer);
1151         }
1152
1153         if (PhotonServerSettings.HostType == ServerSettings.HostingOption.BestRegion)
1154         {
1155             return ConnectToBestCloudServer(gameVersion);
1156         }
1157
1158         return networkingPeer.ConnectToRegionMaster(PhotonServerSettings.PreferredRegion);
1159     }
File name: PhotonNetwork.cs Copy
1213     /// The ping result can be overridden via PhotonNetwork.OverrideBestCloudServer(..)
1221     /// - Invalid AppId (calls: OnFailedToConnectToPhoton(). check exact AppId value)
1222     /// - Network issues (calls: OnFailedToConnectToPhoton())
1223     /// - Invalid region (calls: OnConnectionFail() with DisconnectCause.InvalidRegion)
1224     /// - Subscription CCU limit reached (calls: OnConnectionFail() with DisconnectCause.MaxCcuReached. also calls: OnPhotonMaxCccuReached())
1231     public static bool ConnectToBestCloudServer(string gameVersion)
1232     {
1233         if (PhotonServerSettings == null)
1234         {
1235             Debug.LogError("Can't connect: Loading settings failed. ServerSettings asset must be in any 'Resources' folder as: " + PhotonNetwork.serverSettingsAssetFile);
1236             return false;
1237         }
1238
1239         if (PhotonServerSettings.HostType == ServerSettings.HostingOption.OfflineMode)
1240         {
1241             return PhotonNetwork.ConnectUsingSettings(gameVersion);
1242         }
1243
1244         networkingPeer.IsInitialConnect = true;
1245         networkingPeer.SetApp(PhotonServerSettings.AppID, gameVersion);
1246
1247         CloudRegionCode bestFromPrefs = PhotonHandler.BestRegionCodeInPreferences;
1248         if (bestFromPrefs != CloudRegionCode.none)
1249         {
1250             Debug.Log("Best region found in PlayerPrefs. Connecting to: " + bestFromPrefs);
1251             return networkingPeer.ConnectToRegionMaster(bestFromPrefs);
1252         }
1253
1254         bool couldConnect = PhotonNetwork.networkingPeer.ConnectToNameServer();
1255         return couldConnect;
1256     }
File name: PhotonNetwork.cs Copy
1263     public static void OverrideBestCloudServer(CloudRegionCode region)
1264     {
1265         PhotonHandler.BestRegionCodeInPreferences = region;
1266     }

Best 164 lượt xem

Gõ tìm kiếm nhanh...