Version
How do I use Version
Below are practical examples compiled from projects for learning and reference purposes
Featured Snippets
File name: PhotonConverter.cs
Copy
18 public static void RunConversion()
19 {
20 //Ask if user has made a backup.
21 int option = EditorUtility.DisplayDialogComplex("Conversion", "Attempt automatic conversion from Unity Networking to Photon Unity Networking \"PUN\"?", "Yes", "No!", "Pick Script Folder");
22 switch (option)
23 {
24 case 0:
25 break;
26 case 1:
27 return;
28 case 2:
29 PickFolderAndConvertScripts();
30 return;
31 default:
32 return;
33 }
34
35 //REAAAALY?
36 bool result = EditorUtility.DisplayDialog("Conversion", "Disclaimer: The code conversion feature is quite crude, but should do it's job well (see the sourcecode). A backup is therefore strongly recommended!", "Yes, I've made a backup: GO", "Abort");
37 if (!result)
38 {
39 return;
40 }
41 Output(EditorApplication.timeSinceStartup + " Started conversion of Unity networking -> Photon");
42
43 //Ask to save current scene (optional)
44 EditorApplication.SaveCurrentSceneIfUserWantsTo();
45
46 EditorUtility.DisplayProgressBar("Converting..", "Starting.", 0);
47
48 //Convert NetworkViews to PhotonViews in Project prefabs
49 //Ask the user if we can move all prefabs to a resources folder
50 bool movePrefabs = EditorUtility.DisplayDialog("Conversion", "Can all prefabs that use a PhotonView be moved to a Resources/ folder? You need this if you use Network.Instantiate.", "Yes", "No");
51
52
53 string[] prefabs = Directory.GetFiles("Assets/", "*.prefab", SearchOption.AllDirectories);
54 foreach (string prefab in prefabs)
55 {
56 EditorUtility.DisplayProgressBar("Converting..", "Object:" + prefab, 0.6f);
57
58 Object[] objs = (Object[])AssetDatabase.LoadAllAssetsAtPath(prefab);
59 int converted = 0;
60 foreach (Object obj in objs)
61 {
62 if (obj != null && obj.GetType() == typeof(GameObject))
63 converted += ConvertNetworkView(((GameObject)obj).GetComponents
64 }
65 if (movePrefabs && converted > 0)
66 {
67 //This prefab needs to be under the root of a Resources folder!
68 string path = prefab.Replace("\\", "/");
69 int lastSlash = path.LastIndexOf("/");
70 int resourcesIndex = path.LastIndexOf("/Resources/");
71 if (resourcesIndex != lastSlash - 10)
72 {
73 if (path.Contains("/Resources/"))
74 {
75 Debug.LogWarning("Warning, prefab [" + prefab + "] was already in a resources folder. But has been placed in the root of another one!");
76 }
77 //This prefab NEEDS to be placed under a resources folder
78 string resourcesFolder = path.Substring(0, lastSlash) + "/Resources/";
79 EnsureFolder(resourcesFolder);
80 string newPath = resourcesFolder + path.Substring(lastSlash + 1);
81 string error = AssetDatabase.MoveAsset(prefab, newPath);
82 if (error != "")
83 Debug.LogError(error);
84 Output("Fixed prefab [" + prefab + "] by moving it into a resources folder.");
85 }
86 }
87 }
88
89 //Convert NetworkViews to PhotonViews in scenes
90 string[] sceneFiles = Directory.GetFiles("Assets/", "*.unity", SearchOption.AllDirectories);
91 foreach (string sceneName in sceneFiles)
92 {
93 EditorApplication.OpenScene(sceneName);
94 EditorUtility.DisplayProgressBar("Converting..", "Scene:" + sceneName, 0.2f);
95
96 int converted2 = ConvertNetworkView((NetworkView[])GameObject.FindObjectsOfType(typeof(NetworkView)), true);
97 if (converted2 > 0)
98 {
99 //This will correct all prefabs: The prefabs have gotten new components, but the correct ID's were lost in this case
100 PhotonViewHandler.HierarchyChange(); //TODO: most likely this is triggered on change or on save
101
102 Output("Replaced " + converted2 + " NetworkViews with PhotonViews in scene: " + sceneName);
103 EditorApplication.SaveScene(EditorApplication.currentScene);
104 }
105
106 }
107
108 //Convert C#/JS scripts (API stuff)
109 List
110
111 EditorUtility.DisplayProgressBar("Converting..", "Scripts..", 0.9f);
112 ConvertScripts(scripts);
113
114 Output(EditorApplication.timeSinceStartup + " Completed conversion!");
115 EditorUtility.ClearProgressBar();
116
117 EditorUtility.DisplayDialog("Completed the conversion", "Don't forget to add \"PhotonNetwork.ConnectWithDefaultSettings();\" to connect to the Photon server before using any multiplayer functionality.", "OK");
118 }
File name: PhotonConverter.cs
Copy
120 public static void PickFolderAndConvertScripts()
121 {
122 string folderPath = EditorUtility.OpenFolderPanel("Pick source folder to convert", Directory.GetCurrentDirectory(), "");
123 if (string.IsNullOrEmpty(folderPath))
124 {
125 EditorUtility.DisplayDialog("Script Conversion", "No folder was selected. No files were changed. Please start over.", "Ok.");
126 return;
127 }
128
129 bool result = EditorUtility.DisplayDialog("Script Conversion", "Scripts in this folder will be modified:\n\n" + folderPath + "\n\nMake sure you have backups of these scripts.\nConversion is not guaranteed to work!", "Backup done. Go!", "Abort");
130 if (!result)
131 {
132 return;
133 }
134
135 List
136 ConvertScripts(scripts);
137
138 EditorUtility.DisplayDialog("Script Conversion", "Scripts are now converted to PUN.\n\nYou will need to update\n- scenes\n- components\n- prefabs and\n- add \"PhotonNetwork.ConnectWithDefaultSettings();\"", "Ok");
139 }
File name: PhotonConverter.cs
Copy
160 static void ConvertScripts(List161 {
162 bool ignoreWarningIsLogged = false;
163
164 foreach (string script in scriptPathList)
165 {
166 if (script.Contains("PhotonNetwork")) //Don't convert this file (and others)
167 {
168 if (!ignoreWarningIsLogged)
169 {
170 ignoreWarningIsLogged = true;
171 Debug.LogWarning("Conversion to PUN ignores all files with \"PhotonNetwork\" in their file-path.\nCheck: " + script);
172 }
173 continue;
174 }
175 if (script.Contains("Image Effects"))
176 {
177 continue;
178 }
179
180 ConvertToPhotonAPI(script);
181 }
182
183 foreach (string script in scriptPathList)
184 {
185 AssetDatabase.ImportAsset(script, ImportAssetOptions.ForceUpdate);
186 }
187 }
File name: PhotonConverter.cs
Copy
395 static void ConversionError(string file, string str)
396 {
397 Debug.LogError("Scrip conversion[" + file + "]: " + str);
398 }
File name: PhotonEditor.cs
Copy
543 protected virtual void OnGuiMainWizard()
544 {
545 GUILayout.BeginHorizontal();
546 GUILayout.FlexibleSpace();
547 GUILayout.Label(WizardIcon);
548 GUILayout.FlexibleSpace();
549 GUILayout.EndHorizontal();
550
551 EditorGUILayout.Separator();
552
553 GUILayout.Label(CurrentLang.PUNWizardLabel, EditorStyles.boldLabel);
554 if (isPunPlus)
555 {
556 GUILayout.Label(CurrentLang.MobilePunPlusExportNoteLabel);
557 }
558 else if (!InternalEditorUtility.HasAdvancedLicenseOnBuildTarget(BuildTarget.Android) || !InternalEditorUtility.HasAdvancedLicenseOnBuildTarget(BuildTarget.iOS))
559 {
560 GUILayout.Label(CurrentLang.MobileExportNoteLabel);
561 }
562 EditorGUILayout.Separator();
563
564
565 // settings button
566 GUILayout.BeginHorizontal();
567 GUILayout.Label(CurrentLang.SettingsButton, EditorStyles.boldLabel, GUILayout.Width(100));
568 if (GUILayout.Button(new GUIContent(CurrentLang.SetupButton, CurrentLang.SetupServerCloudLabel)))
569 {
570 this.InitPhotonSetupWindow();
571 }
572
573 GUILayout.EndHorizontal();
574 EditorGUILayout.Separator();
575
576
577 // find / select settings asset
578 GUILayout.BeginHorizontal();
579 GUILayout.Label(CurrentLang.SettingsFileLabel, EditorStyles.boldLabel, GUILayout.Width(100));
580 if (GUILayout.Button(new GUIContent(CurrentLang.LocateSettingsButton, CurrentLang.SettingsHighlightLabel)))
581 {
582 EditorGUIUtility.PingObject(PhotonEditor.Current);
583 }
584
585 GUILayout.EndHorizontal();
586
587
588 GUILayout.FlexibleSpace();
589
590 // converter
591 GUILayout.BeginHorizontal();
592 GUILayout.Label(CurrentLang.ConverterLabel, EditorStyles.boldLabel, GUILayout.Width(100));
593 if (GUILayout.Button(new GUIContent(CurrentLang.StartButton, CurrentLang.UNtoPUNLabel)))
594 {
595 PhotonConverter.RunConversion();
596 }
597
598 GUILayout.EndHorizontal();
599 EditorGUILayout.Separator();
600
601
602 // documentation
603 GUILayout.BeginHorizontal();
604 GUILayout.Label(CurrentLang.DocumentationLabel, EditorStyles.boldLabel, GUILayout.Width(100));
605 GUILayout.BeginVertical();
606 if (GUILayout.Button(new GUIContent(CurrentLang.OpenPDFText, CurrentLang.OpenPDFTooltip)))
607 {
608 EditorUtility.OpenWithDefaultApp(DocumentationLocation);
609 }
610
611 if (GUILayout.Button(new GUIContent(CurrentLang.OpenDevNetText, CurrentLang.OpenDevNetTooltip)))
612 {
613 EditorUtility.OpenWithDefaultApp(UrlDevNet);
614 }
615
616 if (GUILayout.Button(new GUIContent(CurrentLang.OpenCloudDashboardText, CurrentLang.OpenCloudDashboardTooltip)))
617 {
618 EditorUtility.OpenWithDefaultApp(UrlCloudDashboard + Uri.EscapeUriString(this.emailAddress));
619 }
620
621 if (GUILayout.Button(new GUIContent(CurrentLang.OpenForumText, CurrentLang.OpenForumTooltip)))
622 {
623 EditorUtility.OpenWithDefaultApp(UrlForum);
624 }
625
626 GUILayout.EndVertical();
627 GUILayout.EndHorizontal();
628 }
File name: LoadbalancingPeer.cs
Copy
358 public virtual bool OpAuthenticate(string appId, string appVersion, string userId, AuthenticationValues authValues, string regionCode)
359 {
360 if (this.DebugOut >= DebugLevel.INFO)
361 {
362 this.Listener.DebugReturn(DebugLevel.INFO, "OpAuthenticate()");
363 }
364
365 Dictionary
366 if (authValues != null && authValues.Secret != null)
367 {
368 opParameters[ParameterCode.Secret] = authValues.Secret;
369 return this.OpCustom(OperationCode.Authenticate, opParameters, true, (byte)0, false);
370 }
371
372 opParameters[ParameterCode.AppVersion] = appVersion;
373 opParameters[ParameterCode.ApplicationId] = appId;
374
375 if (!string.IsNullOrEmpty(regionCode))
376 {
377 opParameters[ParameterCode.Region] = regionCode;
378 }
379
380 if (!string.IsNullOrEmpty(userId))
381 {
382 opParameters[ParameterCode.UserId] = userId;
383 }
384
385
386 if (authValues != null && authValues.AuthType != CustomAuthenticationType.None)
387 {
388 if (!this.IsEncryptionAvailable)
389 {
390 this.Listener.DebugReturn(DebugLevel.ERROR, "OpAuthenticate() failed. When you want Custom Authentication encryption is mandatory.");
391 return false;
392 }
393
394 opParameters[ParameterCode.ClientAuthenticationType] = (byte)authValues.AuthType;
395 if (!string.IsNullOrEmpty(authValues.Secret))
396 {
397 opParameters[ParameterCode.Secret] = authValues.Secret;
398 }
399 //else
400 //{
401 if (!string.IsNullOrEmpty(authValues.AuthParameters))
402 {
403 opParameters[ParameterCode.ClientAuthenticationParams] = authValues.AuthParameters;
404 }
405 if (authValues.AuthPostData != null)
406 {
407 opParameters[ParameterCode.ClientAuthenticationData] = authValues.AuthPostData;
408 }
409 //}
410 }
411
412 bool sent = this.OpCustom(OperationCode.Authenticate, opParameters, true, (byte)0, this.IsEncryptionAvailable);
413 if (!sent)
414 {
415 this.Listener.DebugReturn(DebugLevel.ERROR, "Error calling OpAuthenticate! Did not work. Check log output, CustomAuthenticationValues and if you're connected.");
416 }
417 return sent;
418 }
File name: NetworkingPeer.cs
Copy
27 {
28 get { return string.Format("{0}_{1}", mAppVersion, PhotonNetwork.versionPUN); }
29 }
File name: NetworkingPeer.cs
Copy
336 public bool ConnectToRegionMaster(CloudRegionCode region)
337 {
338 if (PhotonHandler.AppQuits)
339 {
340 Debug.LogWarning("Ignoring Connect() because app gets closed. If this is an error, check PhotonHandler.AppQuits.");
341 return false;
342 }
343
344 IsUsingNameServer = true;
345 this.CloudRegion = region;
346
347 if (this.State == global::PeerState.ConnectedToNameServer)
348 {
349 return this.OpAuthenticate(this.mAppId, this.mAppVersionPun, this.PlayerName, this.CustomAuthenticationValues, region.ToString());
350 }
351
352 #if RHTTP
353 string address = (this.UsedProtocol == ConnectionProtocol.RHttp) ? this.NameServerAddressHttp : this.NameServerAddress;
354 #else
355 string address = this.NameServerAddress;
356 #endif
357
358 if (!address.Contains(":"))
359 {
360 int port = 0;
361 ProtocolToNameServerPort.TryGetValue(this.UsedProtocol, out port);
362 address = string.Format("{0}:{1}", address, port);
363 //Debug.Log("Server to connect to: "+ address + " settings protocol: " + PhotonNetwork.PhotonServerSettings.Protocol);
364 }
365 if (!base.Connect(address, "ns"))
366 {
367 return false;
368 }
369
370 this.State = global::PeerState.ConnectingToNameServer;
371 return true;
372 }
File name: NetworkingPeer.cs
Copy
1411 public void OnStatusChanged(StatusCode statusCode)
1412 {
1413 if (PhotonNetwork.logLevel >= PhotonLogLevel.Informational)
1414 Debug.Log(string.Format("OnStatusChanged: {0}", statusCode.ToString()));
1415
1416 switch (statusCode)
1417 {
1418 case StatusCode.Connect:
1419 if (this.State == global::PeerState.ConnectingToNameServer)
1420 {
1421 if (PhotonNetwork.logLevel >= PhotonLogLevel.Full)
1422 Debug.Log("Connected to NameServer.");
1423
1424 this.server = ServerConnection.NameServer;
1425 if (this.CustomAuthenticationValues != null)
1426 {
1427 this.CustomAuthenticationValues.Secret = null; // when connecting to NameServer, invalidate any auth values
1428 }
1429 }
1430
1431 if (this.State == global::PeerState.ConnectingToGameserver)
1432 {
1433 if (PhotonNetwork.logLevel >= PhotonLogLevel.Full)
1434 Debug.Log("Connected to gameserver.");
1435
1436 this.server = ServerConnection.GameServer;
1437 this.State = global::PeerState.ConnectedToGameserver;
1438 }
1439
1440 if (this.State == global::PeerState.ConnectingToMasterserver)
1441 {
1442 if (PhotonNetwork.logLevel >= PhotonLogLevel.Full)
1443 Debug.Log("Connected to masterserver.");
1444
1445 this.server = ServerConnection.MasterServer;
1446 this.State = global::PeerState.ConnectedToMaster;
1447
1448 if (this.IsInitialConnect)
1449 {
1450 this.IsInitialConnect = false; // after handling potential initial-connect issues with special messages, we are now sure we can reach a server
1451 SendMonoMessage(PhotonNetworkingMessage.OnConnectedToPhoton);
1452 }
1453 }
1454
1455 this.EstablishEncryption(); // always enable encryption
1456
1457 if (this.IsAuthorizeSecretAvailable)
1458 {
1459 // if we have a token we don't have to wait for encryption (it is encrypted anyways, so encryption is just optional later on)
1460 this.didAuthenticate = this.OpAuthenticate(this.mAppId, this.mAppVersionPun, this.PlayerName, this.CustomAuthenticationValues, this.CloudRegion.ToString());
1461 if (this.didAuthenticate)
1462 {
1463 this.State = global::PeerState.Authenticating;
1464 }
1465 }
1466 break;
1467
1468 case StatusCode.EncryptionEstablished:
1469 // on nameserver, the "process" is stopped here, so the developer/game can either get regions or authenticate with a specific region
1470 if (this.server == ServerConnection.NameServer)
1471 {
1472 this.State = global::PeerState.ConnectedToNameServer;
1473
1474 if (!this.didAuthenticate && this.CloudRegion == CloudRegionCode.none)
1475 {
1476 // this client is not setup to connect to a default region. find out which regions there are!
1477 this.OpGetRegions(this.mAppId);
1478 }
1479 }
1480
1481 // we might need to authenticate automatically now, so the client can do anything at all
1482 if (!this.didAuthenticate && (!this.IsUsingNameServer || this.CloudRegion != CloudRegionCode.none))
1483 {
1484 // once encryption is availble, the client should send one (secure) authenticate. it includes the AppId (which identifies your app on the Photon Cloud)
1485 this.didAuthenticate = this.OpAuthenticate(this.mAppId, this.mAppVersionPun, this.PlayerName, this.CustomAuthenticationValues, this.CloudRegion.ToString());
1486 if (this.didAuthenticate)
1487 {
1488 this.State = global::PeerState.Authenticating;
1489 }
1490 }
1491 break;
1492
1493 case StatusCode.EncryptionFailedToEstablish:
1494 Debug.LogError("Encryption wasn't established: " + statusCode + ". Going to authenticate anyways.");
1495 this.OpAuthenticate(this.mAppId, this.mAppVersionPun, this.PlayerName, this.CustomAuthenticationValues, this.CloudRegion.ToString()); // TODO: check if there are alternatives
1496 break;
1497
1498 case StatusCode.Disconnect:
1499 this.didAuthenticate = false;
1500 this.isFetchingFriends = false;
1501 if (server == ServerConnection.GameServer) this.LeftRoomCleanup();
1502 if (server == ServerConnection.MasterServer) this.LeftLobbyCleanup();
1503
1504 if (this.State == global::PeerState.DisconnectingFromMasterserver)
1505 {
1506 if (this.Connect(this.mGameserver, ServerConnection.GameServer))
1507 {
1508 this.State = global::PeerState.ConnectingToGameserver;
1509 }
1510 }
1511 else if (this.State == global::PeerState.DisconnectingFromGameserver || this.State == global::PeerState.DisconnectingFromNameServer)
1512 {
1513 if (this.Connect(this.MasterServerAddress, ServerConnection.MasterServer))
1514 {
1515 this.State = global::PeerState.ConnectingToMasterserver;
1516 }
1517 }
1518 else
1519 {
1520 if (this.CustomAuthenticationValues != null)
1521 {
1522 this.CustomAuthenticationValues.Secret = null; // invalidate any custom auth secrets
1523 }
1524
1525 this.State = global::PeerState.PeerCreated; // if we set another state here, we could keep clients from connecting in OnDisconnectedFromPhoton right here.
1526 SendMonoMessage(PhotonNetworkingMessage.OnDisconnectedFromPhoton);
1527 }
1528 break;
1529
1530 case StatusCode.SecurityExceptionOnConnect:
1531 case StatusCode.ExceptionOnConnect:
1532 this.State = global::PeerState.PeerCreated;
1533 if (this.CustomAuthenticationValues != null)
1534 {
1535 this.CustomAuthenticationValues.Secret = null; // invalidate any custom auth secrets
1536 }
1537
1538 DisconnectCause cause = (DisconnectCause)statusCode;
1539 SendMonoMessage(PhotonNetworkingMessage.OnFailedToConnectToPhoton, cause);
1540 break;
1541
1542 case StatusCode.Exception:
1543 if (this.IsInitialConnect)
1544 {
1545 Debug.LogError("Exception while connecting to: " + this.ServerAddress + ". Check if the server is available.");
1546 if (this.ServerAddress == null || this.ServerAddress.StartsWith("127.0.0.1"))
1547 {
1548 Debug.LogWarning("The server address is 127.0.0.1 (localhost): Make sure the server is running on this machine. Android and iOS emulators have their own localhost.");
1549 if (this.ServerAddress == this.mGameserver)
1550 {
1551 Debug.LogWarning("This might be a misconfiguration in the game server config. You need to edit it to a (public) address.");
1552 }
1553 }
1554
1555 this.State = global::PeerState.PeerCreated;
1556 cause = (DisconnectCause)statusCode;
1557 SendMonoMessage(PhotonNetworkingMessage.OnFailedToConnectToPhoton, cause);
1558 }
1559 else
1560 {
1561 this.State = global::PeerState.PeerCreated;
1562
1563 cause = (DisconnectCause)statusCode;
1564 SendMonoMessage(PhotonNetworkingMessage.OnConnectionFail, cause);
1565 }
1566
1567 this.Disconnect();
1568 break;
1569
1570 case StatusCode.TimeoutDisconnect:
1571 case StatusCode.ExceptionOnReceive:
1572 case StatusCode.DisconnectByServer:
1573 case StatusCode.DisconnectByServerLogic:
1574 case StatusCode.DisconnectByServerUserLimit:
1575 if (this.IsInitialConnect)
1576 {
1577 Debug.LogWarning(statusCode + " while connecting to: " + this.ServerAddress + ". Check if the server is available.");
1578
1579 cause = (DisconnectCause)statusCode;
1580 SendMonoMessage(PhotonNetworkingMessage.OnFailedToConnectToPhoton, cause);
1581 }
1582 else
1583 {
1584 cause = (DisconnectCause)statusCode;
1585 SendMonoMessage(PhotonNetworkingMessage.OnConnectionFail, cause);
1586 }
1587 if (this.CustomAuthenticationValues != null)
1588 {
1589 this.CustomAuthenticationValues.Secret = null; // invalidate any custom auth secrets
1590 }
1591
1592 this.Disconnect();
1593 break;
1594
1595 case StatusCode.SendError:
1596 // this.mListener.clientErrorReturn(statusCode);
1597 break;
1598
1599 case StatusCode.QueueOutgoingReliableWarning:
1600 case StatusCode.QueueOutgoingUnreliableWarning:
1601 case StatusCode.QueueOutgoingAcksWarning:
1602 case StatusCode.QueueSentWarning:
1603 // this.mListener.warningReturn(statusCode);
1604 break;
1605
1606 case StatusCode.QueueIncomingReliableWarning:
1607 case StatusCode.QueueIncomingUnreliableWarning:
1608 Debug.Log(statusCode + ". This client buffers many incoming messages. This is OK temporarily. With lots of these warnings, check if you send too much or execute messages too slow. " + (PhotonNetwork.isMessageQueueRunning? "":"Your isMessageQueueRunning is false. This can cause the issue temporarily.") );
1609 break;
1610
1611 // // TCP "routing" is an option of Photon that's not currently needed (or supported) by PUN
1612 //case StatusCode.TcpRouterResponseOk:
1613 // break;
1614 //case StatusCode.TcpRouterResponseEndpointUnknown:
1615 //case StatusCode.TcpRouterResponseNodeIdUnknown:
1616 //case StatusCode.TcpRouterResponseNodeNotReady:
1617
1618 // this.DebugReturn(DebugLevel.ERROR, "Unexpected router response: " + statusCode);
1619 // break;
1620
1621 default:
1622
1623 // this.mListener.serverErrorReturn(statusCode.value());
1624 Debug.LogError("Received unknown status code: " + statusCode);
1625 break;
1626 }
1627
1628 this.externalListener.OnStatusChanged(statusCode);
1629 }
File name: NetworkingPeer.cs
Copy
3693 public void SetApp(string appId, string gameVersion)
3694 {
3695 this.mAppId = appId.Trim();
3696
3697 if (!string.IsNullOrEmpty(gameVersion))
3698 {
3699 this.mAppVersion = gameVersion.Trim();
3700 }
3701 }
Download file with original file name:Version
Version 330 lượt xem
Gõ tìm kiếm nhanh...