Last









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

Featured Snippets


File name: PickupController.cs Copy
151     void Update()
152     {
153         if (isControllable)
154         {
155             if (Input.GetButtonDown("Jump"))
156             {
157                 lastJumpButtonTime = Time.time;
158             }
159
160             UpdateSmoothedMovementDirection();
161
162             // Apply gravity
163             // - extra power jump modifies gravity
164             // - controlledDescent mode modifies gravity
165             ApplyGravity();
166
167             // Apply jumping logic
168             ApplyJumping();
169
170
171             // Calculate actual motion
172             Vector3 movement = moveDirection * moveSpeed + new Vector3(0, verticalSpeed, 0) + inAirVelocity;
173             movement *= Time.deltaTime;
174
175             //Debug.Log(movement.x.ToString("0.000") + ":" + movement.z.ToString("0.000"));
176
177             // Move the controller
178             CharacterController controller = GetComponent();
179             collisionFlags = controller.Move(movement);
180
181         }
182
183         // PUN: if a remote position is known, we smooth-move to it (being late(r) but smoother)
184         if (this.remotePosition != Vector3.zero)
185         {
186             transform.position = Vector3.Lerp(transform.position, this.remotePosition, Time.deltaTime * this.RemoteSmoothing);
187         }
188
189         velocity = (transform.position - lastPos)*25;
190
191         // ANIMATION sector
192         if (_animation)
193         {
194             if (_characterState == PickupCharacterState.Jumping)
195             {
196                 if (!jumpingReachedApex)
197                 {
198                     _animation[jumpPoseAnimation.name].speed = jumpAnimationSpeed;
199                     _animation[jumpPoseAnimation.name].wrapMode = WrapMode.ClampForever;
200                     _animation.CrossFade(jumpPoseAnimation.name);
201                 }
202                 else
203                 {
204                     _animation[jumpPoseAnimation.name].speed = -landAnimationSpeed;
205                     _animation[jumpPoseAnimation.name].wrapMode = WrapMode.ClampForever;
206                     _animation.CrossFade(jumpPoseAnimation.name);
207                 }
208             }
209             else
210             {
211                 if (_characterState == PickupCharacterState.Idle)
212                 {
213                     _animation.CrossFade(idleAnimation.name);
214                 }
215                 else if (_characterState == PickupCharacterState.Running)
216                 {
217                     _animation[runAnimation.name].speed = runMaxAnimationSpeed;
218                     if (this.isControllable)
219                     {
220                         _animation[runAnimation.name].speed = Mathf.Clamp(velocity.magnitude, 0.0f, runMaxAnimationSpeed);
221                     }
222                     _animation.CrossFade(runAnimation.name);
223                 }
224                 else if (_characterState == PickupCharacterState.Trotting)
225                 {
226                     _animation[walkAnimation.name].speed = trotMaxAnimationSpeed;
227                     if (this.isControllable)
228                     {
229                         _animation[walkAnimation.name].speed = Mathf.Clamp(velocity.magnitude, 0.0f, trotMaxAnimationSpeed);
230                     }
231                     _animation.CrossFade(walkAnimation.name);
232                 }
233                 else if (_characterState == PickupCharacterState.Walking)
234                 {
235                     _animation[walkAnimation.name].speed = walkMaxAnimationSpeed;
236                     if (this.isControllable)
237                     {
238                         _animation[walkAnimation.name].speed = Mathf.Clamp(velocity.magnitude, 0.0f, walkMaxAnimationSpeed);
239                     }
240                     _animation.CrossFade(walkAnimation.name);
241                 }
242
243                 if (_characterState != PickupCharacterState.Running)
244                 {
245                     _animation[runAnimation.name].time = 0.0f;
246                 }
247             }
248         }
249         // ANIMATION sector
250
251         // Set rotation to the move direction
252         if (IsGrounded())
253         {
254             // a specialty of this controller: you can disable rotation!
255             if (DoRotate)
256             {
257                 transform.rotation = Quaternion.LookRotation(moveDirection);
258             }
259         }
260         else
261         {
262             /* This causes choppy behaviour when colliding with SIDES
263              * Vector3 xzMove = velocity;
264             xzMove.y = 0;
265             if (xzMove.sqrMagnitude > 0.001f)
266             {
267                 transform.rotation = Quaternion.LookRotation(xzMove);
268             }*/
269         }
270
271         // We are in jump mode but just became grounded
272         if (IsGrounded())
273         {
274             lastGroundedTime = Time.time;
275             inAirVelocity = Vector3.zero;
276             if (jumping)
277             {
278                 jumping = false;
279                 SendMessage("DidLand", SendMessageOptions.DontRequireReceiver);
280             }
281         }
282
283         lastPos = transform.position;
284     }
File name: RPGMovement.cs Copy
51     void UpdateAnimation()
52     {
53         Vector3 movementVector = transform.position - m_LastPosition;
54
55         float speed = Vector3.Dot( movementVector.normalized, transform.forward );
56         float direction = Vector3.Dot( movementVector.normalized, transform.right );
57
58         if( Mathf.Abs( speed ) < 0.2f )
59         {
60             speed = 0f;
61         }
62
63         if( speed > 0.6f )
64         {
65             speed = 1f;
66             direction = 0f;
67         }
68
69         if( speed >= 0f )
70         {
71             if( Mathf.Abs( direction ) > 0.7f )
72             {
73                 speed = 1f;
74             }
75         }
76
77         m_AnimatorSpeed = Mathf.MoveTowards( m_AnimatorSpeed, speed, Time.deltaTime * 5f );
78
79         m_Animator.SetFloat( "Speed", m_AnimatorSpeed );
80         m_Animator.SetFloat( "Direction", direction );
81
82         m_LastPosition = transform.position;
83     }
File name: CubeExtra.cs Copy
21     // this method is called by PUN when this script is being "observed" by a PhotonView (setup in inspector)
22     public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
23     {
24         // Always send transform (depending on reliability of the network view)
25         if (stream.isWriting)
26         {
27             Vector3 pos = transform.localPosition;
28             Quaternion rot = transform.localRotation;
29             stream.Serialize(ref pos);
30             stream.Serialize(ref rot);
31         }
32         // When receiving, buffer the information
33         else
34         {
35             // Receive latest state information
36             Vector3 pos = Vector3.zero;
37             Quaternion rot = Quaternion.identity;
38             stream.Serialize(ref pos);
39             stream.Serialize(ref rot);
40
41             lastMovement = (pos - latestCorrectPos) / (Time.time - lastTime);
42
43             lastTime = Time.time;
44             latestCorrectPos = pos;
45
46             transform.position = latestCorrectPos;
47         }
48     }
File name: CubeExtra.cs Copy
50     // This only runs where the component is enabled, which is only on remote peers (server/clients)
51     public void Update()
52     {
53         transform.localPosition += lastMovement * Time.deltaTime;
54     }
File name: ThirdPersonController.cs Copy
292     void Update()
293     {
294         if (isControllable)
295         {
296             if (Input.GetButtonDown("Jump"))
297             {
298                 lastJumpButtonTime = Time.time;
299             }
300
301             UpdateSmoothedMovementDirection();
302
303             // Apply gravity
304             // - extra power jump modifies gravity
305             // - controlledDescent mode modifies gravity
306             ApplyGravity();
307
308             // Apply jumping logic
309             ApplyJumping();
310
311
312             // Calculate actual motion
313             Vector3 movement = moveDirection * moveSpeed + new Vector3(0, verticalSpeed, 0) + inAirVelocity;
314             movement *= Time.deltaTime;
315
316             // Move the controller
317             CharacterController controller = GetComponent();
318             collisionFlags = controller.Move(movement);
319         }
320         velocity = (transform.position - lastPos)*25;
321
322         // ANIMATION sector
323         if (_animation)
324         {
325             if (_characterState == CharacterState.Jumping)
326             {
327                 if (!jumpingReachedApex)
328                 {
329                     _animation[jumpPoseAnimation.name].speed = jumpAnimationSpeed;
330                     _animation[jumpPoseAnimation.name].wrapMode = WrapMode.ClampForever;
331                     _animation.CrossFade(jumpPoseAnimation.name);
332                 }
333                 else
334                 {
335                     _animation[jumpPoseAnimation.name].speed = -landAnimationSpeed;
336                     _animation[jumpPoseAnimation.name].wrapMode = WrapMode.ClampForever;
337                     _animation.CrossFade(jumpPoseAnimation.name);
338                 }
339             }
340             else
341             {
342                 if (this.isControllable && velocity.sqrMagnitude < 0.001f)
343                 {
344                     _characterState = CharacterState.Idle;
345                     _animation.CrossFade(idleAnimation.name);
346                 }
347                 else
348                 {
349                     if (_characterState == CharacterState.Idle)
350                     {
351                         _animation.CrossFade(idleAnimation.name);
352                     }
353                     else if (_characterState == CharacterState.Running)
354                     {
355                         _animation[runAnimation.name].speed = runMaxAnimationSpeed;
356                         if (this.isControllable)
357                         {
358                             _animation[runAnimation.name].speed = Mathf.Clamp(velocity.magnitude, 0.0f, runMaxAnimationSpeed);
359                         }
360                         _animation.CrossFade(runAnimation.name);
361                     }
362                     else if (_characterState == CharacterState.Trotting)
363                     {
364                         _animation[walkAnimation.name].speed = trotMaxAnimationSpeed;
365                         if (this.isControllable)
366                         {
367                             _animation[walkAnimation.name].speed = Mathf.Clamp(velocity.magnitude, 0.0f, trotMaxAnimationSpeed);
368                         }
369                         _animation.CrossFade(walkAnimation.name);
370                     }
371                     else if (_characterState == CharacterState.Walking)
372                     {
373                         _animation[walkAnimation.name].speed = walkMaxAnimationSpeed;
374                         if (this.isControllable)
375                         {
376                             _animation[walkAnimation.name].speed = Mathf.Clamp(velocity.magnitude, 0.0f, walkMaxAnimationSpeed);
377                         }
378                         _animation.CrossFade(walkAnimation.name);
379                     }
380
381                 }
382             }
383         }
384         // ANIMATION sector
385
386         // Set rotation to the move direction
387         if (IsGrounded())
388         {
389
390             transform.rotation = Quaternion.LookRotation(moveDirection);
391
392         }
393         else
394         {
395             /* This causes choppy behaviour when colliding with SIDES
396              * Vector3 xzMove = velocity;
397             xzMove.y = 0;
398             if (xzMove.sqrMagnitude > 0.001f)
399             {
400                 transform.rotation = Quaternion.LookRotation(xzMove);
401             }*/
402         }
403
404         // We are in jump mode but just became grounded
405         if (IsGrounded())
406         {
407             lastGroundedTime = Time.time;
408             inAirVelocity = Vector3.zero;
409             if (jumping)
410             {
411                 jumping = false;
412                 SendMessage("DidLand", SendMessageOptions.DontRequireReceiver);
413             }
414         }
415
416         lastPos = transform.position;
417     }
File name: ThirdPersonController.cs Copy
466     public bool IsGroundedWithTimeout()
467     {
468         return lastGroundedTime + groundedTimeout > Time.time;
469     }
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(), false);
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 scripts = GetScriptsInFolder("Assets");
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
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: PhotonEditor.cs Copy
336     // called in editor, opens wizard for initial setup, keeps scene PhotonViews up to date and closes connections when compiling (to avoid issues)
337     private static void EditorUpdate()
338     {
339         if (dontCheckPunSetup || PhotonEditor.Current == null)
340         {
341             return;
342         }
343
344         // serverSetting is null when the file gets deleted. otherwise, the wizard should only run once and only if hosting option is not (yet) set
345         if (!PhotonEditor.Current.DisableAutoOpenWizard && PhotonEditor.Current.HostType == ServerSettings.HostingOption.NotSet)
346         {
347             ShowRegistrationWizard();
348         }
349
350         // Workaround for TCP crash. Plus this surpresses any other recompile errors.
351         if (EditorApplication.isCompiling)
352         {
353             if (PhotonNetwork.connected)
354             {
355                 if (lastWarning > EditorApplication.timeSinceStartup - 3)
356                 {
357                     // Prevent error spam
358                     Debug.LogWarning(CurrentLang.WarningPhotonDisconnect);
359                     lastWarning = EditorApplication.timeSinceStartup;
360                 }
361
362                 PhotonNetwork.Disconnect();
363             }
364         }
365     }
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     }

Download file with original file name:Last

Last 135 lượt xem

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