PhotonMono









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

Featured Snippets


File name: PhotonConverter.cs Copy
189     static void ConvertToPhotonAPI(string file)
190     {
191         string text = File.ReadAllText(file);
192
193         bool isJS = file.Contains(".js");
194
195         file = file.Replace("\\", "/"); // Get Class name for JS
196         string className = file.Substring(file.LastIndexOf("/")+1);
197         className = className.Substring(0, className.IndexOf("."));
198
199
200         //REGEXP STUFF
201         //Valid are: Space { } , /n /r
202         //string NOT_VAR = @"([^A-Za-z0-9_\[\]\.]+)";
203         string NOT_VAR_WITH_DOT = @"([^A-Za-z0-9_]+)";
204
205         //string VAR_NONARRAY = @"[^A-Za-z0-9_]";
206
207
208         //NetworkView
209         {
210             text = PregReplace(text, NOT_VAR_WITH_DOT + "NetworkView" + NOT_VAR_WITH_DOT, "$1PhotonView$2");
211             text = PregReplace(text, NOT_VAR_WITH_DOT + "networkView" + NOT_VAR_WITH_DOT, "$1photonView$2");
212             text = PregReplace(text, NOT_VAR_WITH_DOT + "stateSynchronization" + NOT_VAR_WITH_DOT, "$1synchronization$2");
213             text = PregReplace(text, NOT_VAR_WITH_DOT + "NetworkStateSynchronization" + NOT_VAR_WITH_DOT, "$1ViewSynchronization$2"); // map Unity enum to ours
214             //.RPC
215             text = PregReplace(text, NOT_VAR_WITH_DOT + "RPCMode.Server" + NOT_VAR_WITH_DOT, "$1PhotonTargets.MasterClient$2");
216             text = PregReplace(text, NOT_VAR_WITH_DOT + "RPCMode" + NOT_VAR_WITH_DOT, "$1PhotonTargets$2");
217         }
218
219         //NetworkMessageInfo: 100%
220         {
221             text = PregReplace(text, NOT_VAR_WITH_DOT + "NetworkMessageInfo" + NOT_VAR_WITH_DOT, "$1PhotonMessageInfo$2");
222             text = PregReplace(text, NOT_VAR_WITH_DOT + "networkView" + NOT_VAR_WITH_DOT, "$1photonView$2");
223         }
224
225         //NetworkViewID:
226         {
227             text = PregReplace(text, NOT_VAR_WITH_DOT + "NetworkViewID" + NOT_VAR_WITH_DOT, "$1int$2"); //We simply use an int
228         }
229
230         //NetworkPlayer
231         {
232             text = PregReplace(text, NOT_VAR_WITH_DOT + "NetworkPlayer" + NOT_VAR_WITH_DOT, "$1PhotonPlayer$2");
233         }
234
235         //Network
236         {
237             //Monobehaviour callbacks
238             {
239                 text = PregReplace(text, NOT_VAR_WITH_DOT + "OnPlayerConnected" + NOT_VAR_WITH_DOT, "$1OnPhotonPlayerConnected$2");
240                 text = PregReplace(text, NOT_VAR_WITH_DOT + "OnPlayerDisconnected" + NOT_VAR_WITH_DOT, "$1OnPhotonPlayerDisconnected$2");
241                 text = PregReplace(text, NOT_VAR_WITH_DOT + "OnNetworkInstantiate" + NOT_VAR_WITH_DOT, "$1OnPhotonInstantiate$2");
242                 text = PregReplace(text, NOT_VAR_WITH_DOT + "OnSerializeNetworkView" + NOT_VAR_WITH_DOT, "$1OnPhotonSerializeView$2");
243                 text = PregReplace(text, NOT_VAR_WITH_DOT + "BitStream" + NOT_VAR_WITH_DOT, "$1PhotonStream$2");
244
245                 //Not completely the same meaning
246                 text = PregReplace(text, NOT_VAR_WITH_DOT + "OnServerInitialized" + NOT_VAR_WITH_DOT, "$1OnCreatedRoom$2");
247                 text = PregReplace(text, NOT_VAR_WITH_DOT + "OnConnectedToServer" + NOT_VAR_WITH_DOT, "$1OnJoinedRoom$2");
248
249                 text = PregReplace(text, NOT_VAR_WITH_DOT + "OnFailedToConnectToMasterServer" + NOT_VAR_WITH_DOT, "$1OnFailedToConnectToPhoton$2");
250                 text = PregReplace(text, NOT_VAR_WITH_DOT + "OnFailedToConnect" + NOT_VAR_WITH_DOT, "$1OnFailedToConnect_OBSELETE$2");
251             }
252
253             //Variables
254             {
255
256                 text = PregReplace(text, NOT_VAR_WITH_DOT + "Network.connections" + NOT_VAR_WITH_DOT, "$1PhotonNetwork.playerList$2");
257                 text = PregReplace(text, NOT_VAR_WITH_DOT + "Network.isServer" + NOT_VAR_WITH_DOT, "$1PhotonNetwork.isMasterClient$2");
258                 text = PregReplace(text, NOT_VAR_WITH_DOT + "Network.isClient" + NOT_VAR_WITH_DOT, "$1PhotonNetwork.isNonMasterClientInRoom$2");
259
260                 text = PregReplace(text, NOT_VAR_WITH_DOT + "NetworkPeerType" + NOT_VAR_WITH_DOT, "$1ConnectionState$2");
261                 text = PregReplace(text, NOT_VAR_WITH_DOT + "Network.peerType" + NOT_VAR_WITH_DOT, "$1PhotonNetwork.connectionState$2");
262                 text = PregReplace(text, NOT_VAR_WITH_DOT + "ConnectionState.Server" + NOT_VAR_WITH_DOT, "$1PhotonNetwork.isMasterClient$2");
263                 text = PregReplace(text, NOT_VAR_WITH_DOT + "ConnectionState.Client" + NOT_VAR_WITH_DOT, "$1PhotonNetwork.isNonMasterClientInRoom$2");
264                 text = PregReplace(text, NOT_VAR_WITH_DOT + "PhotonNetwork.playerList.Length" + NOT_VAR_WITH_DOT, "$1PhotonNetwork.playerList.Count$2");
265
266                 /*DROPPED:
267                     minimumAllocatableViewIDs
268                     natFacilitatorIP is dropped
269                     natFacilitatorPort is dropped
270                     connectionTesterIP
271                     connectionTesterPort
272                     proxyIP
273                     proxyPort
274                     useProxy
275                     proxyPassword
276                  */
277             }
278
279             //Methods
280             {
281                 text = PregReplace(text, NOT_VAR_WITH_DOT + "Network.InitializeServer" + NOT_VAR_WITH_DOT, "$1PhotonNetwork.CreateRoom$2");
282                 text = PregReplace(text, NOT_VAR_WITH_DOT + "Network.Connect" + NOT_VAR_WITH_DOT, "$1PhotonNetwork.JoinRoom$2");
283                 text = PregReplace(text, NOT_VAR_WITH_DOT + "Network.GetAveragePing" + NOT_VAR_WITH_DOT, "$1PhotonNetwork.GetPing$2");
284                 text = PregReplace(text, NOT_VAR_WITH_DOT + "Network.GetLastPing" + NOT_VAR_WITH_DOT, "$1PhotonNetwork.GetPing$2");
285                 /*DROPPED:
286                     TestConnection
287                     TestConnectionNAT
288                     HavePublicAddress
289                 */
290             }
291
292             //Overall
293             text = PregReplace(text, NOT_VAR_WITH_DOT + "Network" + NOT_VAR_WITH_DOT, "$1PhotonNetwork$2");
294
295
296         //Changed methods
297              string ignoreMe = @"([A-Za-z0-9_\[\]\(\) ]+)";
298
299          text = PregReplace(text, NOT_VAR_WITH_DOT + "PhotonNetwork.GetPing\\(" + ignoreMe+"\\);", "$1PhotonNetwork.GetPing();");
300         text = PregReplace(text, NOT_VAR_WITH_DOT + "PhotonNetwork.CloseConnection\\(" + ignoreMe+","+ignoreMe+"\\);", "$1PhotonNetwork.CloseConnection($2);");
301
302         }
303
304         //General
305         {
306             if (text.Contains("Photon")) //Only use the PhotonMonoBehaviour if we use photonView and friends.
307             {
308                 if (isJS)//JS
309                 {
310                     if (text.Contains("extends MonoBehaviour"))
311                         text = PregReplace(text, "extends MonoBehaviour", "extends Photon.MonoBehaviour");
312                     else
313                         text = "class " + className + " extends Photon.MonoBehaviour {\n" + text + "\n}";
314                 }
315                 else //C#
316                     text = PregReplace(text, ": MonoBehaviour", ": Photon.MonoBehaviour");
317             }
318         }
319
320         File.WriteAllText(file, text);
321     }
File name: PhotonViewHandler.cs Copy
25     internal static void HierarchyChange()
26     {
27         if (Application.isPlaying)
28         {
29             //Debug.Log("HierarchyChange ignored, while running.");
30             CheckSceneForStuckHandlers = true; // done once AFTER play mode.
31             return;
32         }
33
34         if (CheckSceneForStuckHandlers)
35         {
36             CheckSceneForStuckHandlers = false;
37             PhotonNetwork.InternalCleanPhotonMonoFromSceneIfStuck();
38         }
39
40         HashSet pvInstances = new HashSet();
41         HashSet usedInstanceViewNumbers = new HashSet();
42         bool fixedSomeId = false;
43
44         //// the following code would be an option if we only checked scene objects (but we can check all PVs)
45         //PhotonView[] pvObjects = GameObject.FindSceneObjectsOfType(typeof(PhotonView)) as PhotonView[];
46         //Debug.Log("HierarchyChange. PV Count: " + pvObjects.Length);
47
48         string levelName = Application.loadedLevelName;
49         #if UNITY_EDITOR
50         levelName = System.IO.Path.GetFileNameWithoutExtension(EditorApplication.currentScene);
51         #endif
52         int minViewIdInThisScene = PunSceneSettings.MinViewIdForScene(levelName);
53         //Debug.Log("Level '" + Application.loadedLevelName + "' has a minimum ViewId of: " + minViewIdInThisScene);
54
55         PhotonView[] pvObjects = Resources.FindObjectsOfTypeAll(typeof(PhotonView)) as PhotonView[];
56
57         foreach (PhotonView view in pvObjects)
58         {
59             // first pass: fix prefabs to viewID 0 if they got a view number assigned (cause they should not have one!)
60             if (EditorUtility.IsPersistent(view.gameObject))
61             {
62                 if (view.viewID != 0 || view.prefixBackup != -1 || view.instantiationId != -1)
63                 {
64                     Debug.LogWarning("PhotonView on persistent object being fixed (id and prefix must be 0). Was: " + view);
65                     view.viewID = 0;
66                     view.prefixBackup = -1;
67                     view.instantiationId = -1;
68                     EditorUtility.SetDirty(view);
69                     fixedSomeId = true;
70                 }
71             }
72             else
73             {
74                 // keep all scene-instanced PVs for later re-check
75                 pvInstances.Add(view);
76             }
77         }
78
79         Dictionary idPerObject = new Dictionary();
80
81         // second pass: check all used-in-scene viewIDs for duplicate viewIDs (only checking anything non-prefab)
82         // scene-PVs must have user == 0 (scene/room) and a subId != 0
83         foreach (PhotonView view in pvInstances)
84         {
85             if (view.ownerId > 0)
86             {
87                 Debug.Log("Re-Setting Owner ID of: " + view);
88             }
89             view.ownerId = 0; // simply make sure no owner is set (cause room always uses 0)
90             view.prefix = -1; // TODO: prefix could be settable via inspector per scene?!
91
92             if (view.viewID != 0)
93             {
94                 if (view.viewID < minViewIdInThisScene || usedInstanceViewNumbers.Contains(view.viewID))
95                 {
96                     view.viewID = 0; // avoid duplicates and negative values by assigning 0 as (temporary) number to be fixed in next pass
97                 }
98                 else
99                 {
100                     usedInstanceViewNumbers.Add(view.viewID); // builds a list of currently used viewIDs
101
102                     int instId = 0;
103                     if (idPerObject.TryGetValue(view.gameObject, out instId))
104                     {
105                         view.instantiationId = instId;
106                     }
107                     else
108                     {
109                         view.instantiationId = view.viewID;
110                         idPerObject[view.gameObject] = view.instantiationId;
111                     }
112                 }
113             }
114
115         }
116
117         // third pass: anything that's now 0 must get a new (not yet used) ID (starting at 0)
118         int lastUsedId = (minViewIdInThisScene > 0) ? minViewIdInThisScene - 1 : 0;
119
120         foreach (PhotonView view in pvInstances)
121         {
122             if (view.viewID == 0)
123             {
124                 // Debug.LogWarning("setting scene ID: " + view.gameObject.name + " ID: " + view.subId.ID + " scene ID: " + view.GetSceneID() + " IsPersistent: " + EditorUtility.IsPersistent(view.gameObject) + " IsSceneViewIDFree: " + IsSceneViewIDFree(view.subId.ID, view));
125                 int nextViewId = PhotonViewHandler.GetID(lastUsedId, usedInstanceViewNumbers);
126
127                 view.viewID = nextViewId;
128
129                 int instId = 0;
130                 if (idPerObject.TryGetValue(view.gameObject, out instId))
131                 {
132                     Debug.Log("Set inst ID");
133                     view.instantiationId = instId;
134                 }
135                 else
136                 {
137                     view.instantiationId = view.viewID;
138                     idPerObject[view.gameObject] = nextViewId;
139                 }
140
141                 //// when using the Editor's serialization (view.subId in this case), this is not needed, it seems
142                 //PrefabUtility.RecordPrefabInstancePropertyModifications(view);
143
144                 lastUsedId = nextViewId;
145                 EditorUtility.SetDirty(view);
146                 fixedSomeId = true;
147             }
148         }
149
150
151         if (fixedSomeId)
152         {
153             //Debug.LogWarning("Some subId was adjusted."); // this log is only interesting for Exit Games
154         }
155     }
File name: PhotonNetwork.cs Copy
644     {
645         get
646         {
647             return 1000 / sendInterval;
648         }
649
650         set
651         {
652             sendInterval = 1000 / value;
653             if (photonMono != null)
654             {
655                 photonMono.updateInterval = sendInterval;
656             }
657
658             if (value < sendRateOnSerialize)
659             {
660                 // sendRateOnSerialize needs to be <= sendRate
661                 sendRateOnSerialize = value;
662             }
663         }
664     }
File name: PhotonNetwork.cs Copy
674     {
675         get
676         {
677             return 1000 / sendIntervalOnSerialize;
678         }
679
680         set
681         {
682             if (value > sendRate)
683             {
684                 Debug.LogError("Error, can not set the OnSerialize SendRate more often then the overall SendRate");
685                 value = sendRate;
686             }
687
688             sendIntervalOnSerialize = 1000 / value;
689             if (photonMono != null)
690             {
691                 photonMono.updateIntervalOnSerialize = sendIntervalOnSerialize;
692             }
693         }
694     }
File name: PhotonNetwork.cs Copy
974     static PhotonNetwork()
975     {
976         #if UNITY_EDITOR
977         if (!EditorApplication.isPlaying && !EditorApplication.isPlayingOrWillChangePlaymode)
978         {
979             //Debug.Log(string.Format("PhotonNetwork.ctor() Not playing {0} {1}", UnityEditor.EditorApplication.isPlaying, UnityEditor.EditorApplication.isPlayingOrWillChangePlaymode));
980             return;
981         }
982
983         // This can happen when you recompile a script IN play made
984         // This helps to surpress some errors, but will not fix breaking
985         PhotonHandler[] photonHandlers = GameObject.FindObjectsOfType(typeof(PhotonHandler)) as PhotonHandler[];
986         if (photonHandlers != null && photonHandlers.Length > 0)
987         {
988             Debug.LogWarning("Unity recompiled. Connection gets closed and replaced. You can connect as 'new' client.");
989             foreach (PhotonHandler photonHandler in photonHandlers)
990             {
991                 //Debug.Log("Handler: " + photonHandler + " photonHandler.gameObject: " + photonHandler.gameObject);
992                 photonHandler.gameObject.hideFlags = 0;
993                 GameObject.DestroyImmediate(photonHandler.gameObject);
994                 Component.DestroyImmediate(photonHandler);
995             }
996         }
997         #endif
998
999         Application.runInBackground = true;
1000
1001         // Set up a MonoBehaviour to run Photon, and hide it
1002         GameObject photonGO = new GameObject();
1003         photonMono = (PhotonHandler)photonGO.AddComponent();
1004         photonGO.name = "PhotonMono";
1005         photonGO.hideFlags = HideFlags.HideInHierarchy;
1006
1007
1008         // Set up the NetworkingPeer and use protocol of PhotonServerSettings
1009         networkingPeer = new NetworkingPeer(photonMono, string.Empty, PhotonNetwork.PhotonServerSettings.Protocol);
1010
1011
1012         // Local player
1013         CustomTypes.Register();
1014     }
File name: PhotonNetwork.cs Copy
1025     /// Connect(serverAddress, , appID, gameVersion)
1036     public static void SwitchToProtocol(ConnectionProtocol cp)
1037     {
1038         if (networkingPeer.UsedProtocol == cp)
1039         {
1040             return;
1041         }
1042         try
1043         {
1044             networkingPeer.Disconnect();
1045             networkingPeer.StopThread();
1046         }
1047         catch
1048         {
1049
1050         }
1051
1052         // set up a new NetworkingPeer
1053         NetworkingPeer newPeer = new NetworkingPeer(photonMono, String.Empty, cp);
1054         newPeer.mAppVersion = networkingPeer.mAppVersion;
1055         newPeer.CustomAuthenticationValues = networkingPeer.CustomAuthenticationValues;
1056         newPeer.PlayerName= networkingPeer.PlayerName;
1057         newPeer.mLocalActor = networkingPeer.mLocalActor;
1058         newPeer.DebugOut = networkingPeer.DebugOut;
1059         newPeer.CrcEnabled = networkingPeer.CrcEnabled;
1060         newPeer.lobby = networkingPeer.lobby;
1061         newPeer.LimitOfUnreliableCommands = networkingPeer.LimitOfUnreliableCommands;
1062         newPeer.SentCountAllowance = networkingPeer.SentCountAllowance;
1063         newPeer.TrafficStatsEnabled = networkingPeer.TrafficStatsEnabled;
1064
1065         networkingPeer = newPeer;
1066         Debug.LogWarning("Protocol switched to: " + cp + ".");
1067     }
File name: PhotonNetwork.cs Copy
1072     public static void InternalCleanPhotonMonoFromSceneIfStuck()
1073     {
1074         PhotonHandler[] photonHandlers = GameObject.FindObjectsOfType(typeof(PhotonHandler)) as PhotonHandler[];
1075         if (photonHandlers != null && photonHandlers.Length > 0)
1076         {
1077             Debug.Log("Cleaning up hidden PhotonHandler instances in scene. Please save it. This is not an issue.");
1078             foreach (PhotonHandler photonHandler in photonHandlers)
1079             {
1080                 // Debug.Log("Removing Handler: " + photonHandler + " photonHandler.gameObject: " + photonHandler.gameObject);
1081                 photonHandler.gameObject.hideFlags = 0;
1082
1083                 if (photonHandler.gameObject != null && photonHandler.gameObject.name == "PhotonMono")
1084                 {
1085                     GameObject.DestroyImmediate(photonHandler.gameObject);
1086                 }
1087
1088                 Component.DestroyImmediate(photonHandler);
1089             }
1090         }
1091     }

PhotonMono 178 lượt xem

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