ViewID
How do I use View I D
Below are practical examples compiled from projects for learning and reference purposes
Featured Snippets
File name: ThirdPersonNetwork.cs
Copy
9 void Awake()
10 {
11 cameraScript = GetComponent
12 controllerScript = GetComponent
13
14 if (photonView.isMine)
15 {
16 //MINE: local player, simply enable the local scripts
17 cameraScript.enabled = true;
18 controllerScript.enabled = true;
19 }
20 else
21 {
22 cameraScript.enabled = false;
23
24 controllerScript.enabled = true;
25 controllerScript.isControllable = false;
26 }
27
28 gameObject.name = gameObject.name + photonView.viewID;
29 }
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: PhotonConverter.cs
Copy
351 static int ConvertNetworkView(NetworkView[] netViews, bool isScene)
352 {
353 for (int i = netViews.Length - 1; i >= 0; i--)
354 {
355 NetworkView netView = netViews[i];
356 PhotonView view = netView.gameObject.AddComponent
357 if (isScene)
358 {
359 //Get scene ID
360 string str = netView.viewID.ToString().Replace("SceneID: ", "");
361 int firstSpace = str.IndexOf(" ");
362 str = str.Substring(0, firstSpace);
363 int oldViewID = int.Parse(str);
364
365 view.viewID = oldViewID;
366 EditorUtility.SetDirty(view);
367 EditorUtility.SetDirty(view.gameObject);
368 }
369 view.observed = netView.observed;
370 if (netView.stateSynchronization == NetworkStateSynchronization.Unreliable)
371 {
372 view.synchronization = ViewSynchronization.Unreliable;
373 }
374 else if (netView.stateSynchronization == NetworkStateSynchronization.ReliableDeltaCompressed)
375 {
376 view.synchronization = ViewSynchronization.ReliableDeltaCompressed;
377 }
378 else
379 {
380 view.synchronization = ViewSynchronization.Off;
381 }
382 DestroyImmediate(netView, true);
383 }
384 AssetDatabase.Refresh();
385 AssetDatabase.SaveAssets();
386
387 return netViews.Length;
388 }
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
41 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
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: PhotonViewInspector.cs
Copy
21 public override void OnInspectorGUI()
22 {
23 #if UNITY_3_5
24 EditorGUIUtility.LookLikeInspector();
25 #endif
26 //EditorGUI.indentLevel = 1;
27
28 m_Target = (PhotonView)this.target;
29 bool isProjectPrefab = EditorUtility.IsPersistent(m_Target.gameObject);
30
31 if( m_Target.ObservedComponents == null )
32 {
33 m_Target.ObservedComponents = new System.Collections.Generic.List
34 }
35
36 if( m_Target.ObservedComponents.Count == 0 )
37 {
38 m_Target.ObservedComponents.Add( null );
39 }
40
41 EditorGUILayout.BeginHorizontal();
42 // Owner
43 if (isProjectPrefab)
44 {
45 EditorGUILayout.LabelField("Owner:", "Set at runtime");
46 }
47 else if (m_Target.isSceneView)
48 {
49 EditorGUILayout.LabelField("Owner", "Scene");
50 }
51 else
52 {
53 PhotonPlayer owner = m_Target.owner;
54 string ownerInfo = (owner != null) ? owner.name : "
55
56 if (string.IsNullOrEmpty(ownerInfo))
57 {
58 ownerInfo = "
59 }
60
61 EditorGUILayout.LabelField("Owner", "[" + m_Target.ownerId + "] " + ownerInfo);
62 }
63
64 // ownership requests
65 EditorGUI.BeginDisabledGroup(Application.isPlaying);
66 m_Target.ownershipTransfer = (OwnershipOption)EditorGUILayout.EnumPopup(m_Target.ownershipTransfer, GUILayout.Width(100));
67 EditorGUI.EndDisabledGroup();
68
69 EditorGUILayout.EndHorizontal();
70
71
72 // View ID
73 if (isProjectPrefab)
74 {
75 EditorGUILayout.LabelField("View ID", "Set at runtime");
76 }
77 else if (EditorApplication.isPlaying)
78 {
79 EditorGUILayout.LabelField("View ID", m_Target.viewID.ToString());
80 }
81 else
82 {
83 int idValue = EditorGUILayout.IntField("View ID [1.."+(PhotonNetwork.MAX_VIEW_IDS-1)+"]", m_Target.viewID);
84 m_Target.viewID = idValue;
85 }
86
87
88
89 // Locally Controlled
90 if (EditorApplication.isPlaying)
91 {
92 string masterClientHint = PhotonNetwork.isMasterClient ? "(master)" : "";
93 EditorGUILayout.Toggle("Controlled locally: " + masterClientHint, m_Target.isMine);
94 }
95
96
97
98 //DrawOldObservedItem();
99 ConvertOldObservedItemToObservedList();
100
101
102 // ViewSynchronization (reliability)
103 if (m_Target.synchronization == ViewSynchronization.Off)
104 {
105 GUI.color = Color.grey;
106 }
107
108 EditorGUILayout.PropertyField( serializedObject.FindProperty( "synchronization" ), new GUIContent( "Observe option:" ) );
109
110 if( m_Target.synchronization != ViewSynchronization.Off &&
111 m_Target.ObservedComponents.FindAll( item => item != null ).Count == 0 )
112 {
113 GUILayout.BeginVertical( GUI.skin.box );
114 GUILayout.Label( "Warning", EditorStyles.boldLabel );
115 GUILayout.Label( "Setting the synchronization option only makes sense if you observe something." );
116 GUILayout.EndVertical();
117 }
118
119 /*ViewSynchronization vsValue = (ViewSynchronization)EditorGUILayout.EnumPopup("Observe option:", m_Target.synchronization);
120 if (vsValue != m_Target.synchronization)
121 {
122 m_Target.synchronization = vsValue;
123 if (m_Target.synchronization != ViewSynchronization.Off && m_Target.observed == null)
124 {
125 EditorUtility.DisplayDialog("Warning", "Setting the synchronization option only makes sense if you observe something.", "OK, I will fix it.");
126 }
127 }*/
128
129 DrawSpecificTypeSerializationOptions();
130
131 GUI.color = Color.white;
132 DrawObservedComponentsList();
133
134 // Cleanup: save and fix look
135 if (GUI.changed)
136 {
137 EditorUtility.SetDirty(m_Target);
138 PhotonViewHandler.HierarchyChange(); // TODO: check if needed
139 }
140
141 GUI.color = Color.white;
142 EditorGUIUtility.LookLikeControls();
143 }
File name: PunSceneSettings.cs
Copy
70 public static int MinViewIdForScene(string scene)
71 {
72 if (string.IsNullOrEmpty(scene))
73 {
74 return 0;
75 }
76
77 PunSceneSettings pss = Instance;
78 if (pss == null)
79 {
80 Debug.LogError("pss cant be null");
81 return 0;
82 }
83
84 foreach (SceneSetting setting in pss.MinViewIdPerScene)
85 {
86 if (setting.sceneName.Equals(scene))
87 {
88 return setting.minViewId;
89 }
90 }
91 return 0;
92 }
File name: NetworkingPeer.cs
Copy
459 private void LeftRoomCleanup()
460 {
461 bool wasInRoom = mRoomToGetInto != null;
462 // when leaving a room, we clean up depending on that room's settings.
463 bool autoCleanupSettingOfRoom = (this.mRoomToGetInto != null) ? this.mRoomToGetInto.autoCleanUp : PhotonNetwork.autoCleanUpPlayerObjects;
464
465 this.hasSwitchedMC = false;
466 this.mRoomToGetInto = null;
467 this.mActors = new Dictionary
468 this.mPlayerListCopy = new PhotonPlayer[0];
469 this.mOtherPlayerListCopy = new PhotonPlayer[0];
470 this.mMasterClient = null;
471 this.allowedReceivingGroups = new HashSet
472 this.blockSendingGroups = new HashSet
473 this.mGameList = new Dictionary
474 this.mGameListCopy = new RoomInfo[0];
475 this.isFetchingFriends = false;
476
477 this.ChangeLocalID(-1);
478
479 // Cleanup all network objects (all spawned PhotonViews, local and remote)
480 if (autoCleanupSettingOfRoom)
481 {
482 this.LocalCleanupAnythingInstantiated(true);
483 PhotonNetwork.manuallyAllocatedViewIds = new List
484 }
485
486 if (wasInRoom)
487 {
488 SendMonoMessage(PhotonNetworkingMessage.OnLeftRoom);
489 }
490 }
File name: NetworkingPeer.cs
Copy
1631 public void OnEvent(EventData photonEvent)
1632 {
1633 if (PhotonNetwork.logLevel >= PhotonLogLevel.Informational)
1634 Debug.Log(string.Format("OnEvent: {0}", photonEvent.ToString()));
1635
1636 int actorNr = -1;
1637 PhotonPlayer originatingPlayer = null;
1638
1639 if (photonEvent.Parameters.ContainsKey(ParameterCode.ActorNr))
1640 {
1641 actorNr = (int)photonEvent[ParameterCode.ActorNr];
1642 if (this.mActors.ContainsKey(actorNr))
1643 {
1644 originatingPlayer = (PhotonPlayer)this.mActors[actorNr];
1645 }
1646 //else
1647 //{
1648 // // the actor sending this event is not in actorlist. this is usually no problem
1649 // if (photonEvent.Code != (byte)LiteOpCode.Join)
1650 // {
1651 // Debug.LogWarning("Received event, but we do not have this actor: " + actorNr);
1652 // }
1653 //}
1654 }
1655
1656 switch (photonEvent.Code)
1657 {
1658 case PunEvent.OwnershipRequest:
1659 {
1660 int[] requestValues = (int[]) photonEvent.Parameters[ParameterCode.CustomEventContent];
1661 int requestedViewId = requestValues[0];
1662 int currentOwner = requestValues[1];
1663 Debug.Log("Ev OwnershipRequest: " + photonEvent.Parameters.ToStringFull() + " ViewID: " + requestedViewId + " from: " + currentOwner + " Time: " + Environment.TickCount%1000);
1664
1665 PhotonView requestedView = PhotonView.Find(requestedViewId);
1666 if (requestedView == null)
1667 {
1668 Debug.LogWarning("Can't find PhotonView of incoming OwnershipRequest. ViewId not found: " + requestedViewId);
1669 break;
1670 }
1671
1672 Debug.Log("Ev OwnershipRequest PhotonView.ownershipTransfer: " + requestedView.ownershipTransfer + " .ownerId: " + requestedView.ownerId + " isOwnerActive: " + requestedView.isOwnerActive + ". This client's player: " + PhotonNetwork.player.ToStringFull());
1673
1674 switch (requestedView.ownershipTransfer)
1675 {
1676 case OwnershipOption.Fixed:
1677 Debug.LogWarning("Ownership mode == fixed. Ignoring request.");
1678 break;
1679 case OwnershipOption.Takeover:
1680 if (currentOwner == requestedView.ownerId)
1681 {
1682 // a takeover is successful automatically, if taken from current owner
1683 requestedView.ownerId = actorNr;
1684 }
1685 break;
1686 case OwnershipOption.Request:
1687 if (currentOwner == PhotonNetwork.player.ID || PhotonNetwork.player.isMasterClient)
1688 {
1689 if ((requestedView.ownerId == PhotonNetwork.player.ID) || (PhotonNetwork.player.isMasterClient && !requestedView.isOwnerActive))
1690 {
1691 SendMonoMessage(PhotonNetworkingMessage.OnOwnershipRequest, new object[] {requestedView, originatingPlayer});
1692 }
1693 }
1694 break;
1695 default:
1696 break;
1697 }
1698 }
1699 break;
1700
1701 case PunEvent.OwnershipTransfer:
1702 {
1703 int[] transferViewToUserID = (int[]) photonEvent.Parameters[ParameterCode.CustomEventContent];
1704 Debug.Log("Ev OwnershipTransfer. ViewID " + transferViewToUserID[0] + " to: " + transferViewToUserID[1] + " Time: " + Environment.TickCount%1000);
1705
1706 int requestedViewId = transferViewToUserID[0];
1707 int newOwnerId = transferViewToUserID[1];
1708
1709 PhotonView pv = PhotonView.Find(requestedViewId);
1710 pv.ownerId = newOwnerId;
1711
1712 break;
1713 }
1714 case EventCode.GameList:
1715 {
1716 this.mGameList = new Dictionary
1717 Hashtable games = (Hashtable)photonEvent[ParameterCode.GameList];
1718 foreach (DictionaryEntry game in games)
1719 {
1720 string gameName = (string)game.Key;
1721 this.mGameList[gameName] = new RoomInfo(gameName, (Hashtable)game.Value);
1722 }
1723 mGameListCopy = new RoomInfo[mGameList.Count];
1724 mGameList.Values.CopyTo(mGameListCopy, 0);
1725 SendMonoMessage(PhotonNetworkingMessage.OnReceivedRoomListUpdate);
1726 break;
1727 }
1728
1729 case EventCode.GameListUpdate:
1730 {
1731 Hashtable games = (Hashtable)photonEvent[ParameterCode.GameList];
1732 foreach (DictionaryEntry room in games)
1733 {
1734 string gameName = (string)room.Key;
1735 RoomInfo game = new RoomInfo(gameName, (Hashtable)room.Value);
1736 if (game.removedFromList)
1737 {
1738 this.mGameList.Remove(gameName);
1739 }
1740 else
1741 {
1742 this.mGameList[gameName] = game;
1743 }
1744 }
1745 this.mGameListCopy = new RoomInfo[this.mGameList.Count];
1746 this.mGameList.Values.CopyTo(this.mGameListCopy, 0);
1747 SendMonoMessage(PhotonNetworkingMessage.OnReceivedRoomListUpdate);
1748 break;
1749 }
1750
1751 case EventCode.QueueState:
1752 // not used anymore
1753 break;
1754
1755 case EventCode.AppStats:
1756 // Debug.LogInfo("Received stats!");
1757 this.mPlayersInRoomsCount = (int)photonEvent[ParameterCode.PeerCount];
1758 this.mPlayersOnMasterCount = (int)photonEvent[ParameterCode.MasterPeerCount];
1759 this.mGameCount = (int)photonEvent[ParameterCode.GameCount];
1760 break;
1761
1762 case EventCode.Join:
1763 // actorNr is fetched out of event above
1764 Hashtable actorProperties = (Hashtable)photonEvent[ParameterCode.PlayerProperties];
1765 if (originatingPlayer == null)
1766 {
1767 bool isLocal = this.mLocalActor.ID == actorNr;
1768 this.AddNewPlayer(actorNr, new PhotonPlayer(isLocal, actorNr, actorProperties));
1769 this.ResetPhotonViewsOnSerialize(); // This sets the correct OnSerializeState for Reliable OnSerialize
1770 }
1771
1772 if (actorNr == this.mLocalActor.ID)
1773 {
1774 // in this player's 'own' join event, we get a complete list of players in the room, so check if we know all players
1775 int[] actorsInRoom = (int[])photonEvent[ParameterCode.ActorList];
1776 foreach (int actorNrToCheck in actorsInRoom)
1777 {
1778 if (this.mLocalActor.ID != actorNrToCheck && !this.mActors.ContainsKey(actorNrToCheck))
1779 {
1780 this.AddNewPlayer(actorNrToCheck, new PhotonPlayer(false, actorNrToCheck, string.Empty));
1781 }
1782 }
1783
1784 // joinWithCreateOnDemand can turn an OpJoin into creating the room. Then actorNumber is 1 and callback: OnCreatedRoom()
1785 if (this.mLastJoinType == JoinType.JoinOrCreateOnDemand && this.mLocalActor.ID == 1)
1786 {
1787 SendMonoMessage(PhotonNetworkingMessage.OnCreatedRoom);
1788 }
1789 SendMonoMessage(PhotonNetworkingMessage.OnJoinedRoom); //Always send OnJoinedRoom
1790
1791 }
1792 else
1793 {
1794 SendMonoMessage(PhotonNetworkingMessage.OnPhotonPlayerConnected, this.mActors[actorNr]);
1795 }
1796 break;
1797
1798 case EventCode.Leave:
1799 this.HandleEventLeave(actorNr);
1800 break;
1801
1802 case EventCode.PropertiesChanged:
1803 int targetActorNr = (int)photonEvent[ParameterCode.TargetActorNr];
1804 Hashtable gameProperties = null;
1805 Hashtable actorProps = null;
1806 if (targetActorNr == 0)
1807 {
1808 gameProperties = (Hashtable)photonEvent[ParameterCode.Properties];
1809 }
1810 else
1811 {
1812 actorProps = (Hashtable)photonEvent[ParameterCode.Properties];
1813 }
1814
1815 this.ReadoutProperties(gameProperties, actorProps, targetActorNr);
1816 break;
1817
1818 case PunEvent.RPC:
1819 //ts: each event now contains a single RPC. execute this
1820 // Debug.Log("Ev RPC from: " + originatingPlayer);
1821 this.ExecuteRPC(photonEvent[ParameterCode.Data] as Hashtable, originatingPlayer);
1822 break;
1823
1824 case PunEvent.SendSerialize:
1825 case PunEvent.SendSerializeReliable:
1826 Hashtable serializeData = (Hashtable)photonEvent[ParameterCode.Data];
1827 //Debug.Log(serializeData.ToStringFull());
1828
1829 int remoteUpdateServerTimestamp = (int)serializeData[(byte)0];
1830 short remoteLevelPrefix = -1;
1831 short initialDataIndex = 1;
1832 if (serializeData.ContainsKey((byte)1))
1833 {
1834 remoteLevelPrefix = (short)serializeData[(byte)1];
1835 initialDataIndex = 2;
1836 }
1837
1838 for (short s = initialDataIndex; s < serializeData.Count; s++)
1839 {
1840 this.OnSerializeRead(serializeData[s] as Hashtable, originatingPlayer, remoteUpdateServerTimestamp, remoteLevelPrefix);
1841 }
1842 break;
1843
1844 case PunEvent.Instantiation:
1845 this.DoInstantiate((Hashtable)photonEvent[ParameterCode.Data], originatingPlayer, null);
1846 break;
1847
1848 case PunEvent.CloseConnection:
1849 // MasterClient "requests" a disconnection from us
1850 if (originatingPlayer == null || !originatingPlayer.isMasterClient)
1851 {
1852 Debug.LogError("Error: Someone else(" + originatingPlayer + ") then the masterserver requests a disconnect!");
1853 }
1854 else
1855 {
1856 PhotonNetwork.LeaveRoom();
1857 }
1858
1859 break;
1860
1861 case PunEvent.DestroyPlayer:
1862 Hashtable evData = (Hashtable)photonEvent[ParameterCode.Data];
1863 int targetPlayerId = (int)evData[(byte)0];
1864 if (targetPlayerId >= 0)
1865 {
1866 this.DestroyPlayerObjects(targetPlayerId, true);
1867 }
1868 else
1869 {
1870 if (this.DebugOut >= DebugLevel.INFO) Debug.Log("Ev DestroyAll! By PlayerId: " + actorNr);
1871 this.DestroyAll(true);
1872 }
1873 break;
1874
1875 case PunEvent.Destroy:
1876 evData = (Hashtable)photonEvent[ParameterCode.Data];
1877 int instantiationId = (int)evData[(byte)0];
1878 // Debug.Log("Ev Destroy for viewId: " + instantiationId + " sent by owner: " + (instantiationId / PhotonNetwork.MAX_VIEW_IDS == actorNr) + " this client is owner: " + (instantiationId / PhotonNetwork.MAX_VIEW_IDS == this.mLocalActor.ID));
1879
1880
1881 PhotonView pvToDestroy = null;
1882 if (this.photonViewList.TryGetValue(instantiationId, out pvToDestroy))
1883 {
1884 this.RemoveInstantiatedGO(pvToDestroy.gameObject, true);
1885 }
1886 else
1887 {
1888 if (this.DebugOut >= DebugLevel.ERROR) Debug.LogError("Ev Destroy Failed. Could not find PhotonView with instantiationId " + instantiationId + ". Sent by actorNr: " + actorNr);
1889 }
1890
1891 break;
1892
1893 case PunEvent.AssignMaster:
1894 evData = (Hashtable)photonEvent[ParameterCode.Data];
1895 int newMaster = (int)evData[(byte)1];
1896 this.SetMasterClient(newMaster, false);
1897 break;
1898
1899 default:
1900 if (photonEvent.Code < 200 && PhotonNetwork.OnEventCall != null)
1901 {
1902 object content = photonEvent[ParameterCode.Data];
1903 PhotonNetwork.OnEventCall(photonEvent.Code, content, actorNr);
1904 }
1905 else
1906 {
1907 // actorNr might be null. it is fetched out of event on top of method
1908 // Hashtable eventContent = (Hashtable) photonEvent[ParameterCode.Data];
1909 // this.mListener.customEventAction(actorNr, eventCode, eventContent);
1910 Debug.LogError("Error. Unhandled event: " + photonEvent);
1911 }
1912 break;
1913 }
1914
1915 this.externalListener.OnEvent(photonEvent);
1916 }
File name: NetworkingPeer.cs
Copy
1918 private void SendVacantViewIds()
1919 {
1920 Debug.Log("SendVacantViewIds()");
1921 List
1922 foreach (PhotonView view in this.photonViewList.Values)
1923 {
1924 if (!view.isOwnerActive)
1925 {
1926 vacantViews.Add(view.viewID);
1927 }
1928 }
1929
1930 Debug.Log("Sending vacant view IDs. Length: " + vacantViews.Count);
1931 //this.OpRaiseEvent(PunEvent.VacantViewIds, true, vacantViews.ToArray());
1932 this.OpRaiseEvent(PunEvent.VacantViewIds, vacantViews.ToArray(), true, null);
1933 }
File name: NetworkingPeer.cs
Copy
1962 public void ExecuteRPC(Hashtable rpcData, PhotonPlayer sender)
1963 {
1964 if (rpcData == null || !rpcData.ContainsKey((byte)0))
1965 {
1966 Debug.LogError("Malformed RPC; this should never occur. Content: " + SupportClass.DictionaryToString(rpcData));
1967 return;
1968 }
1969
1970 // ts: updated with "flat" event data
1971 int netViewID = (int)rpcData[(byte)0]; // LIMITS PHOTONVIEWS&PLAYERS
1972 int otherSidePrefix = 0; // by default, the prefix is 0 (and this is not being sent)
1973 if (rpcData.ContainsKey((byte)1))
1974 {
1975 otherSidePrefix = (short)rpcData[(byte)1];
1976 }
1977
1978 string inMethodName;
1979 if (rpcData.ContainsKey((byte)5))
1980 {
1981 int rpcIndex = (byte)rpcData[(byte)5]; // LIMITS RPC COUNT
1982 if (rpcIndex > PhotonNetwork.PhotonServerSettings.RpcList.Count - 1)
1983 {
1984 Debug.LogError("Could not find RPC with index: " + rpcIndex + ". Going to ignore! Check PhotonServerSettings.RpcList");
1985 return;
1986 }
1987 else
1988 {
1989 inMethodName = PhotonNetwork.PhotonServerSettings.RpcList[rpcIndex];
1990 }
1991 }
1992 else
1993 {
1994 inMethodName = (string)rpcData[(byte)3];
1995 }
1996
1997 object[] inMethodParameters = null;
1998 if (rpcData.ContainsKey((byte)4))
1999 {
2000 inMethodParameters = (object[])rpcData[(byte)4];
2001 }
2002
2003 if (inMethodParameters == null)
2004 {
2005 inMethodParameters = new object[0];
2006 }
2007
2008 PhotonView photonNetview = this.GetPhotonView(netViewID);
2009 if (photonNetview == null)
2010 {
2011 int viewOwnerId = netViewID/PhotonNetwork.MAX_VIEW_IDS;
2012 bool owningPv = (viewOwnerId == this.mLocalActor.ID);
2013 bool ownerSent = (viewOwnerId == sender.ID);
2014
2015 if (owningPv)
2016 {
2017 Debug.LogWarning("Received RPC \"" + inMethodName + "\" for viewID " + netViewID + " but this PhotonView does not exist! View was/is ours." + (ownerSent ? " Owner called." : " Remote called.") + " By: " + sender.ID);
2018 }
2019 else
2020 {
2021 Debug.LogWarning("Received RPC \"" + inMethodName + "\" for viewID " + netViewID + " but this PhotonView does not exist! Was remote PV." + (ownerSent ? " Owner called." : " Remote called.") + " By: " + sender.ID + " Maybe GO was destroyed but RPC not cleaned up.");
2022 }
2023 return;
2024 }
2025
2026 if (photonNetview.prefix != otherSidePrefix)
2027 {
2028 Debug.LogError(
2029 "Received RPC \"" + inMethodName + "\" on viewID " + netViewID + " with a prefix of " + otherSidePrefix
2030 + ", our prefix is " + photonNetview.prefix + ". The RPC has been ignored.");
2031 return;
2032 }
2033
2034 // Get method name
2035 if (inMethodName == string.Empty)
2036 {
2037 Debug.LogError("Malformed RPC; this should never occur. Content: " + SupportClass.DictionaryToString(rpcData));
2038 return;
2039 }
2040
2041 if (PhotonNetwork.logLevel >= PhotonLogLevel.Full)
2042 Debug.Log("Received RPC: " + inMethodName);
2043
2044
2045 // SetReceiving filtering
2046 if (photonNetview.group != 0 && !allowedReceivingGroups.Contains(photonNetview.group))
2047 {
2048 return; // Ignore group
2049 }
2050
2051 Type[] argTypes = new Type[0];
2052 if (inMethodParameters.Length > 0)
2053 {
2054 argTypes = new Type[inMethodParameters.Length];
2055 int i = 0;
2056 for (int index = 0; index < inMethodParameters.Length; index++)
2057 {
2058 object objX = inMethodParameters[index];
2059 if (objX == null)
2060 {
2061 argTypes[i] = null;
2062 }
2063 else
2064 {
2065 argTypes[i] = objX.GetType();
2066 }
2067
2068 i++;
2069 }
2070 }
2071
2072 int receivers = 0;
2073 int foundMethods = 0;
2074 MonoBehaviour[] mbComponents = photonNetview.GetComponents
2075 for (int componentsIndex = 0; componentsIndex < mbComponents.Length; componentsIndex++)
2076 {
2077 MonoBehaviour monob = mbComponents[componentsIndex];
2078 if (monob == null)
2079 {
2080 Debug.LogError("ERROR You have missing MonoBehaviours on your gameobjects!");
2081 continue;
2082 }
2083
2084 Type type = monob.GetType();
2085
2086 // Get [RPC] methods from cache
2087 List
2088 if (this.monoRPCMethodsCache.ContainsKey(type))
2089 {
2090 cachedRPCMethods = this.monoRPCMethodsCache[type];
2091 }
2092
2093 if (cachedRPCMethods == null)
2094 {
2095 List
2096
2097 this.monoRPCMethodsCache[type] = entries;
2098 cachedRPCMethods = entries;
2099 }
2100
2101 if (cachedRPCMethods == null)
2102 {
2103 continue;
2104 }
2105
2106 // Check cache for valid methodname+arguments
2107 for (int index = 0; index < cachedRPCMethods.Count; index++)
2108 {
2109 MethodInfo mInfo = cachedRPCMethods[index];
2110 if (mInfo.Name == inMethodName)
2111 {
2112 foundMethods++;
2113 ParameterInfo[] pArray = mInfo.GetParameters();
2114 if (pArray.Length == argTypes.Length)
2115 {
2116 // Normal, PhotonNetworkMessage left out
2117 if (this.CheckTypeMatch(pArray, argTypes))
2118 {
2119 receivers++;
2120 object result = mInfo.Invoke((object)monob, inMethodParameters);
2121 if (mInfo.ReturnType == typeof(IEnumerator))
2122 {
2123 monob.StartCoroutine((IEnumerator)result);
2124 }
2125 }
2126 }
2127 else if ((pArray.Length - 1) == argTypes.Length)
2128 {
2129 // Check for PhotonNetworkMessage being the last
2130 if (this.CheckTypeMatch(pArray, argTypes))
2131 {
2132 if (pArray[pArray.Length - 1].ParameterType == typeof(PhotonMessageInfo))
2133 {
2134 receivers++;
2135
2136 int sendTime = (int)rpcData[(byte)2];
2137 object[] deParamsWithInfo = new object[inMethodParameters.Length + 1];
2138 inMethodParameters.CopyTo(deParamsWithInfo, 0);
2139 deParamsWithInfo[deParamsWithInfo.Length - 1] = new PhotonMessageInfo(sender, sendTime, photonNetview);
2140
2141 object result = mInfo.Invoke((object)monob, deParamsWithInfo);
2142 if (mInfo.ReturnType == typeof(IEnumerator))
2143 {
2144 monob.StartCoroutine((IEnumerator)result);
2145 }
2146 }
2147 }
2148 }
2149 else if (pArray.Length == 1 && pArray[0].ParameterType.IsArray)
2150 {
2151 receivers++;
2152 object result = mInfo.Invoke((object)monob, new object[] { inMethodParameters });
2153 if (mInfo.ReturnType == typeof(IEnumerator))
2154 {
2155 monob.StartCoroutine((IEnumerator)result);
2156 }
2157 }
2158 }
2159 }
2160 }
2161
2162 // Error handling
2163 if (receivers != 1)
2164 {
2165 string argsString = string.Empty;
2166 for (int index = 0; index < argTypes.Length; index++)
2167 {
2168 Type ty = argTypes[index];
2169 if (argsString != string.Empty)
2170 {
2171 argsString += ", ";
2172 }
2173
2174 if (ty == null)
2175 {
2176 argsString += "null";
2177 }
2178 else
2179 {
2180 argsString += ty.Name;
2181 }
2182 }
2183
2184 if (receivers == 0)
2185 {
2186 if (foundMethods == 0)
2187 {
2188 Debug.LogError("PhotonView with ID " + netViewID + " has no method \"" + inMethodName + "\" marked with the [RPC](C#) or @RPC(JS) property! Args: " + argsString);
2189 }
2190 else
2191 {
2192 Debug.LogError("PhotonView with ID " + netViewID + " has no method \"" + inMethodName + "\" that takes " + argTypes.Length + " argument(s): " + argsString);
2193 }
2194 }
2195 else
2196 {
2197 Debug.LogError("PhotonView with ID " + netViewID + " has " + receivers + " methods \"" + inMethodName + "\" that takes " + argTypes.Length + " argument(s): " + argsString + ". Should be just one?");
2198 }
2199 }
2200 }
ViewID 124 lượt xem
Gõ tìm kiếm nhanh...