-
-
Notifications
You must be signed in to change notification settings - Fork 65
/
NetworkIdentity.cs
1392 lines (1241 loc) · 62.6 KB
/
NetworkIdentity.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Security.Cryptography;
using UnityEngine;
using UnityEngine.Serialization;
#if UNITY_EDITOR
using UnityEditor;
#if UNITY_2018_3_OR_NEWER
using UnityEditor.Experimental.SceneManagement;
#endif
#endif
namespace Mirror
{
/// <summary>
/// The NetworkIdentity identifies objects across the network, between server and clients. Its primary data is a NetworkInstanceId which is allocated by the server and then set on clients. This is used in network communications to be able to lookup game objects on different machines.
/// </summary>
/// <remarks>
/// <para>The NetworkIdentity is used to synchronize information in the object with the network. Only the server should create instances of objects which have NetworkIdentity as otherwise they will not be properly connected to the system.</para>
/// <para>For complex objects with a hierarchy of subcomponents, the NetworkIdentity must be on the root of the hierarchy. It is not supported to have multiple NetworkIdentity components on subcomponents of a hierarchy.</para>
/// <para>NetworkBehaviour scripts require a NetworkIdentity on the game object to be able to function.</para>
/// <para>The NetworkIdentity manages the dirty state of the NetworkBehaviours of the object. When it discovers that NetworkBehaviours are dirty, it causes an update packet to be created and sent to clients.</para>
/// <para>The flow for serialization updates managed by the NetworkIdentity is:</para>
/// <para>* Each NetworkBehaviour has a dirty mask. This mask is available inside OnSerialize as syncVarDirtyBits</para>
/// <para>* Each SyncVar in a NetworkBehaviour script is assigned a bit in the dirty mask.</para>
/// <para>* Changing the value of SyncVars causes the bit for that SyncVar to be set in the dirty mask</para>
/// <para>* Alternatively, calling SetDirtyBit() writes directly to the dirty mask</para>
/// <para>* NetworkIdentity objects are checked on the server as part of it's update loop</para>
/// <para>* If any NetworkBehaviours on a NetworkIdentity are dirty, then an UpdateVars packet is created for that object</para>
/// <para>* The UpdateVars packet is populated by calling OnSerialize on each NetworkBehaviour on the object</para>
/// <para>* NetworkBehaviours that are NOT dirty write a zero to the packet for their dirty bits</para>
/// <para>* NetworkBehaviours that are dirty write their dirty mask, then the values for the SyncVars that have changed</para>
/// <para>* If OnSerialize returns true for a NetworkBehaviour, the dirty mask is reset for that NetworkBehaviour, so it will not send again until its value changes.</para>
/// <para>* The UpdateVars packet is sent to ready clients that are observing the object</para>
/// <para>On the client:</para>
/// <para>* an UpdateVars packet is received for an object</para>
/// <para>* The OnDeserialize function is called for each NetworkBehaviour script on the object</para>
/// <para>* Each NetworkBehaviour script on the object reads a dirty mask.</para>
/// <para>* If the dirty mask for a NetworkBehaviour is zero, the OnDeserialize functions returns without reading any more</para>
/// <para>* If the dirty mask is non-zero value, then the OnDeserialize function reads the values for the SyncVars that correspond to the dirty bits that are set</para>
/// <para>* If there are SyncVar hook functions, those are invoked with the value read from the stream.</para>
/// </remarks>
[ExecuteInEditMode]
[DisallowMultipleComponent]
[AddComponentMenu("Network/NetworkIdentity")]
[HelpURL("https://mirror-networking.com/docs/Components/NetworkIdentity.html")]
public sealed class NetworkIdentity : MonoBehaviour
{
// configuration
NetworkBehaviour[] networkBehavioursCache;
// member used to mark a identity for future reset
// check MarkForReset for more information.
bool reset;
/// <summary>
/// Returns true if running as a client and this object was spawned by a server.
/// </summary>
//
// IMPORTANT: checking NetworkClient.active means that isClient is false in OnDestroy:
// public bool isClient => NetworkClient.active && netId != 0 && !serverOnly;
// but we need it in OnDestroy, e.g. when saving skillbars on quit. this
// works fine if we keep the UNET way of setting isClient manually.
// => fixes https://github.com/vis2k/Mirror/issues/1475
public bool isClient { get; internal set; }
/// <summary>
/// Returns true if NetworkServer.active and server is not stopped.
/// </summary>
//
// IMPORTANT: checking NetworkServer.active means that isServer is false in OnDestroy:
// public bool isServer => NetworkServer.active && netId != 0;
// but we need it in OnDestroy, e.g. when saving players on quit. this
// works fine if we keep the UNET way of setting isServer manually.
// => fixes https://github.com/vis2k/Mirror/issues/1484
public bool isServer { get; internal set; }
/// <summary>
/// This returns true if this object is the one that represents the player on the local machine.
/// <para>This is set when the server has spawned an object for this particular client.</para>
/// </summary>
public bool isLocalPlayer => ClientScene.localPlayer == this;
/// <summary>
/// This returns true if this object is the authoritative player object on the client.
/// <para>This value is determined at runtime. For most objects, authority is held by the server.</para>
/// <para>For objects that had their authority set by AssignClientAuthority on the server, this will be true on the client that owns the object. NOT on other clients.</para>
/// </summary>
public bool hasAuthority { get; internal set; }
/// <summary>
/// The set of network connections (players) that can see this object.
/// <para>null until OnStartServer was called. this is necessary for SendTo* to work properly in server-only mode.</para>
/// </summary>
public Dictionary<int, NetworkConnection> observers;
/// <summary>
/// Unique identifier for this particular object instance, used for tracking objects between networked clients and the server.
/// <para>This is a unique identifier for this particular GameObject instance. Use it to track GameObjects between networked clients and the server.</para>
/// </summary>
public uint netId { get; internal set; }
/// <summary>
/// A unique identifier for NetworkIdentity objects within a scene.
/// <para>This is used for spawning scene objects on clients.</para>
/// </summary>
// persistent scene id <sceneHash/32,sceneId/32> (see AssignSceneID comments)
[FormerlySerializedAs("m_SceneId"), HideInInspector]
public ulong sceneId;
/// <summary>
/// Flag to make this object only exist when the game is running as a server (or host).
/// </summary>
[FormerlySerializedAs("m_ServerOnly")]
public bool serverOnly;
/// <summary>
/// The NetworkConnection associated with this NetworkIdentity. This is only valid for player objects on a local client.
/// </summary>
public NetworkConnection connectionToServer { get; internal set; }
NetworkConnectionToClient _connectionToClient;
/// <summary>
/// The NetworkConnection associated with this <see cref="NetworkIdentity">NetworkIdentity.</see> This is valid for player and other owned objects in the server.
/// <para>Use it to return details such as the connection's identity, IP address and ready status.</para>
/// </summary>
public NetworkConnectionToClient connectionToClient
{
get => _connectionToClient;
internal set
{
if (_connectionToClient != null)
_connectionToClient.RemoveOwnedObject(this);
_connectionToClient = value;
_connectionToClient?.AddOwnedObject(this);
}
}
/// <summary>
/// All spawned NetworkIdentities by netId. Available on server and client.
/// </summary>
public static readonly Dictionary<uint, NetworkIdentity> spawned = new Dictionary<uint, NetworkIdentity>();
public NetworkBehaviour[] NetworkBehaviours
{
get
{
if (networkBehavioursCache == null)
{
CreateNetworkBehavioursCache();
}
return networkBehavioursCache;
}
}
void CreateNetworkBehavioursCache()
{
networkBehavioursCache = GetComponents<NetworkBehaviour>();
if (NetworkBehaviours.Length > 64)
{
Debug.LogError($"Only 64 NetworkBehaviour components are allowed for NetworkIdentity: {name} because of the dirtyComponentMask", this);
// Log error once then resize array so that NetworkIdentity does not throw exceptions later
Array.Resize(ref networkBehavioursCache, 64);
}
}
// NetworkProximityChecker caching
NetworkVisibility visibilityCache;
public NetworkVisibility visibility
{
get
{
if (visibilityCache == null)
{
visibilityCache = GetComponent<NetworkVisibility>();
}
return visibilityCache;
}
}
[SerializeField, HideInInspector] string m_AssetId;
// the AssetId trick:
// - ideally we would have a serialized 'Guid m_AssetId' but Unity can't
// serialize it because Guid's internal bytes are private
// - UNET used 'NetworkHash128' originally, with byte0, ..., byte16
// which works, but it just unnecessary extra code
// - using just the Guid string would work, but it's 32 chars long and
// would then be sent over the network as 64 instead of 16 bytes
// -> the solution is to serialize the string internally here and then
// use the real 'Guid' type for everything else via .assetId
/// <summary>
/// Unique identifier used to find the source assets when server spawns the on clients.
/// </summary>
public Guid assetId
{
get
{
#if UNITY_EDITOR
// This is important because sometimes OnValidate does not run (like when adding view to prefab with no child links)
if (string.IsNullOrEmpty(m_AssetId))
SetupIDs();
#endif
// convert string to Guid and use .Empty to avoid exception if
// we would use 'new Guid("")'
return string.IsNullOrEmpty(m_AssetId) ? Guid.Empty : new Guid(m_AssetId);
}
internal set
{
string newAssetIdString = value.ToString("N");
if (string.IsNullOrEmpty(m_AssetId) || m_AssetId == newAssetIdString)
{
m_AssetId = newAssetIdString;
}
else Debug.LogWarning($"SetDynamicAssetId object {name} already has an assetId {m_AssetId}, new asset id {newAssetIdString}");
}
}
// keep track of all sceneIds to detect scene duplicates
static readonly Dictionary<ulong, NetworkIdentity> sceneIds = new Dictionary<ulong, NetworkIdentity>();
/// <summary>
/// Gets the NetworkIdentity from the sceneIds dictionary with the corresponding id
/// </summary>
/// <param name="id"></param>
/// <returns>NetworkIdentity from the sceneIds dictionary</returns>
public static NetworkIdentity GetSceneIdentity(ulong id) => sceneIds[id];
// used when adding players
internal void SetClientOwner(NetworkConnection conn)
{
// do nothing if it already has an owner
if (connectionToClient != null && conn != connectionToClient)
{
Debug.LogError($"Object {this} netId={netId} already has an owner. Use RemoveClientAuthority() first", this);
return;
}
// otherwise set the owner connection
connectionToClient = (NetworkConnectionToClient)conn;
}
static uint nextNetworkId = 1;
internal static uint GetNextNetworkId() => nextNetworkId++;
/// <summary>
/// Resets nextNetworkId = 1
/// </summary>
public static void ResetNextNetworkId() => nextNetworkId = 1;
/// <summary>
/// The delegate type for the clientAuthorityCallback.
/// </summary>
/// <param name="conn">The network connection that is gaining or losing authority.</param>
/// <param name="identity">The object whose client authority status is being changed.</param>
/// <param name="authorityState">The new state of client authority of the object for the connection.</param>
public delegate void ClientAuthorityCallback(NetworkConnection conn, NetworkIdentity identity, bool authorityState);
/// <summary>
/// A callback that can be populated to be notified when the client-authority state of objects changes.
/// <para>Whenever an object is spawned with client authority, or the client authority status of an object is changed with AssignClientAuthority or RemoveClientAuthority, then this callback will be invoked.</para>
/// <para>This callback is only invoked on the server.</para>
/// </summary>
public static ClientAuthorityCallback clientAuthorityCallback;
// this is used when a connection is destroyed, since the "observers" property is read-only
internal void RemoveObserverInternal(NetworkConnection conn)
{
observers?.Remove(conn.connectionId);
}
void Awake()
{
// detect runtime sceneId duplicates, e.g. if a user tries to
// Instantiate a sceneId object at runtime. if we don't detect it,
// then the client won't know which of the two objects to use for a
// SpawnSceneObject message, and it's likely going to be the wrong
// object.
//
// This might happen if for example we have a Dungeon GameObject
// which contains a Skeleton monster as child, and when a player
// runs into the Dungeon we create a Dungeon Instance of that
// Dungeon, which would duplicate a scene object.
//
// see also: https://github.com/vis2k/Mirror/issues/384
if (Application.isPlaying && sceneId != 0)
{
if (sceneIds.TryGetValue(sceneId, out NetworkIdentity existing) && existing != this)
{
Debug.LogError(name + "'s sceneId: " + sceneId.ToString("X") + " is already taken by: " + existing.name + ". Don't call Instantiate for NetworkIdentities that were in the scene since the beginning (aka scene objects). Otherwise the client won't know which object to use for a SpawnSceneObject message.");
Destroy(gameObject);
}
else
{
sceneIds[sceneId] = this;
}
}
}
void OnValidate()
{
#if UNITY_EDITOR
SetupIDs();
#endif
}
#if UNITY_EDITOR
void AssignAssetID(GameObject prefab) => AssignAssetID(AssetDatabase.GetAssetPath(prefab));
void AssignAssetID(string path) => m_AssetId = AssetDatabase.AssetPathToGUID(path);
bool ThisIsAPrefab() => PrefabUtility.IsPartOfPrefabAsset(gameObject);
bool ThisIsASceneObjectWithPrefabParent(out GameObject prefab)
{
prefab = null;
if (!PrefabUtility.IsPartOfPrefabInstance(gameObject))
{
return false;
}
prefab = PrefabUtility.GetCorrespondingObjectFromSource(gameObject);
if (prefab == null)
{
Debug.LogError("Failed to find prefab parent for scene object [name:" + gameObject.name + "]");
return false;
}
return true;
}
static uint GetRandomUInt()
{
// use Crypto RNG to avoid having time based duplicates
using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
{
byte[] bytes = new byte[4];
rng.GetBytes(bytes);
return BitConverter.ToUInt32(bytes, 0);
}
}
// persistent sceneId assignment
// (because scene objects have no persistent unique ID in Unity)
//
// original UNET used OnPostProcessScene to assign an index based on
// FindObjectOfType<NetworkIdentity> order.
// -> this didn't work because FindObjectOfType order isn't deterministic.
// -> one workaround is to sort them by sibling paths, but it can still
// get out of sync when we open scene2 in editor and we have
// DontDestroyOnLoad objects that messed with the sibling index.
//
// we absolutely need a persistent id. challenges:
// * it needs to be 0 for prefabs
// => we set it to 0 in SetupIDs() if prefab!
// * it needs to be only assigned in edit time, not at runtime because
// only the objects that were in the scene since beginning should have
// a scene id.
// => Application.isPlaying check solves that
// * it needs to detect duplicated sceneIds after duplicating scene
// objects
// => sceneIds dict takes care of that
// * duplicating the whole scene file shouldn't result in duplicate
// scene objects
// => buildIndex is shifted into sceneId for that.
// => if we have no scenes in build index then it doesn't matter
// because by definition a build can't switch to other scenes
// => if we do have scenes in build index then it will be != -1
// note: the duplicated scene still needs to be opened once for it to
// be set properly
// * scene objects need the correct scene index byte even if the scene's
// build index was changed or a duplicated scene wasn't opened yet.
// => OnPostProcessScene is the only function that gets called for
// each scene before runtime, so this is where we set the scene
// byte.
// * disabled scenes in build settings should result in same scene index
// in editor and in build
// => .gameObject.scene.buildIndex filters out disabled scenes by
// default
// * generated sceneIds absolutely need to set scene dirty and force the
// user to resave.
// => Undo.RecordObject does that perfectly.
// * sceneIds should never be generated temporarily for unopened scenes
// when building, otherwise editor and build get out of sync
// => BuildPipeline.isBuildingPlayer check solves that
void AssignSceneID()
{
// we only ever assign sceneIds at edit time, never at runtime.
// by definition, only the original scene objects should get one.
// -> if we assign at runtime then server and client would generate
// different random numbers!
if (Application.isPlaying)
return;
// no valid sceneId yet, or duplicate?
bool duplicate = sceneIds.TryGetValue(sceneId, out NetworkIdentity existing) && existing != null && existing != this;
if (sceneId == 0 || duplicate)
{
// clear in any case, because it might have been a duplicate
sceneId = 0;
// if a scene was never opened and we are building it, then a
// sceneId would be assigned to build but not saved in editor,
// resulting in them getting out of sync.
// => don't ever assign temporary ids. they always need to be
// permanent
// => throw an exception to cancel the build and let the user
// know how to fix it!
if (BuildPipeline.isBuildingPlayer)
throw new Exception("Scene " + gameObject.scene.path + " needs to be opened and resaved before building, because the scene object " + name + " has no valid sceneId yet.");
// if we generate the sceneId then we MUST be sure to set dirty
// in order to save the scene object properly. otherwise it
// would be regenerated every time we reopen the scene, and
// upgrading would be very difficult.
// -> Undo.RecordObject is the new EditorUtility.SetDirty!
// -> we need to call it before changing.
Undo.RecordObject(this, "Generated SceneId");
// generate random sceneId part (0x00000000FFFFFFFF)
uint randomId = GetRandomUInt();
// only assign if not a duplicate of an existing scene id
// (small chance, but possible)
duplicate = sceneIds.TryGetValue(randomId, out existing) && existing != null && existing != this;
if (!duplicate)
{
sceneId = randomId;
//Debug.Log(name + " in scene=" + gameObject.scene.name + " sceneId assigned to: " + m_SceneId.ToString("X"));
}
}
// add to sceneIds dict no matter what
// -> even if we didn't generate anything new, because we still need
// existing sceneIds in there to check duplicates
sceneIds[sceneId] = this;
}
// copy scene path hash into sceneId for scene objects.
// this is the only way for scene file duplication to not contain
// duplicate sceneIds as it seems.
// -> sceneId before: 0x00000000AABBCCDD
// -> then we clear the left 4 bytes, so that our 'OR' uses 0x00000000
// -> then we OR the hash into the 0x00000000 part
// -> buildIndex is not enough, because Editor and Build have different
// build indices if there are disabled scenes in build settings, and
// if no scene is in build settings then Editor and Build have
// different indices too (Editor=0, Build=-1)
// => ONLY USE THIS FROM POSTPROCESSSCENE!
[EditorBrowsable(EditorBrowsableState.Never)]
public void SetSceneIdSceneHashPartInternal()
{
// get deterministic scene hash
uint pathHash = (uint)gameObject.scene.path.GetStableHashCode();
// shift hash from 0x000000FFFFFFFF to 0xFFFFFFFF00000000
ulong shiftedHash = (ulong)pathHash << 32;
// OR into scene id
sceneId = (sceneId & 0xFFFFFFFF) | shiftedHash;
// log it. this is incredibly useful to debug sceneId issues.
if (LogFilter.Debug) Debug.Log(name + " in scene=" + gameObject.scene.name + " scene index hash(" + pathHash.ToString("X") + ") copied into sceneId: " + sceneId.ToString("X"));
}
void SetupIDs()
{
if (ThisIsAPrefab())
{
// force 0 for prefabs
sceneId = 0;
AssignAssetID(gameObject);
}
// are we currently in prefab editing mode? aka prefab stage
// => check prefabstage BEFORE SceneObjectWithPrefabParent
// (fixes https://github.com/vis2k/Mirror/issues/976)
// => if we don't check GetCurrentPrefabStage and only check
// GetPrefabStage(gameObject), then the 'else' case where we
// assign a sceneId and clear the assetId would still be
// triggered for prefabs. in other words: if we are in prefab
// stage, do not bother with anything else ever!
else if (PrefabStageUtility.GetCurrentPrefabStage() != null)
{
// when modifying a prefab in prefab stage, Unity calls
// OnValidate for that prefab and for all scene objects based on
// that prefab.
//
// is this GameObject the prefab that we modify, and not just a
// scene object based on the prefab?
// * GetCurrentPrefabStage = 'are we editing ANY prefab?'
// * GetPrefabStage(go) = 'are we editing THIS prefab?'
if (PrefabStageUtility.GetPrefabStage(gameObject) != null)
{
// force 0 for prefabs
sceneId = 0;
//Debug.Log(name + " @ scene: " + gameObject.scene.name + " sceneid reset to 0 because CurrentPrefabStage=" + PrefabStageUtility.GetCurrentPrefabStage() + " PrefabStage=" + PrefabStageUtility.GetPrefabStage(gameObject));
// NOTE: might make sense to use GetPrefabStage for asset
// path, but let's not touch it while it works.
string path = PrefabStageUtility.GetCurrentPrefabStage().prefabAssetPath;
AssignAssetID(path);
}
}
else if (ThisIsASceneObjectWithPrefabParent(out GameObject prefab))
{
AssignSceneID();
AssignAssetID(prefab);
}
else
{
AssignSceneID();
m_AssetId = "";
}
}
#endif
// Unity will Destroy all networked objects on Scene Change, so we have to handle that here silently.
// That means we cannot have any warning or logging in this method.
void OnDestroy()
{
// remove from sceneIds
// -> remove with (0xFFFFFFFFFFFFFFFF) and without (0x00000000FFFFFFFF)
// sceneHash to be 100% safe.
sceneIds.Remove(sceneId);
sceneIds.Remove(sceneId & 0x00000000FFFFFFFF);
// Only call NetworkServer.Destroy on server and only if reset is false
// reset will be false from incorrect use of Destroy instead of NetworkServer.Destroy
// reset will be true if NetworkServer.Destroy was correctly invoked to begin with
// Users are supposed to call NetworkServer.Destroy instead of just regular Destroy for networked objects.
// This is a safeguard in case users accidentally call regular Destroy instead.
// We cover their mistake by calling NetworkServer.Destroy for them.
// If, however, they call NetworkServer.Destroy correctly, which leads to NetworkIdentity.MarkForReset,
// then we don't need to call it again, so the check for reset is needed to prevent the doubling.
if (isServer && !reset)
{
// Do not add logging to this (see above)
NetworkServer.Destroy(gameObject);
}
}
internal void OnStartServer()
{
// do nothing if already spawned
if (isServer)
return;
// set isServer flag
isServer = true;
// If the instance/net ID is invalid here then this is an object instantiated from a prefab and the server should assign a valid ID
// NOTE: this might not be necessary because the above m_IsServer
// check already checks netId. BUT this case here checks only
// netId, so it would still check cases where isServer=false
// but netId!=0.
if (netId != 0)
{
// This object has already been spawned, this method might be called again
// if we try to respawn all objects. This can happen when we add a scene
// in that case there is nothing else to do.
return;
}
netId = GetNextNetworkId();
observers = new Dictionary<int, NetworkConnection>();
if (LogFilter.Debug) Debug.Log("OnStartServer " + this + " NetId:" + netId + " SceneId:" + sceneId);
// add to spawned (note: the original EnableIsServer isn't needed
// because we already set m_isServer=true above)
spawned[netId] = this;
// in host mode we set isClient true before calling OnStartServer,
// otherwise isClient is false in OnStartServer.
if (NetworkClient.active)
{
isClient = true;
}
foreach (NetworkBehaviour comp in NetworkBehaviours)
{
// an exception in OnStartServer should be caught, so that one
// component's exception doesn't stop all other components from
// being initialized
// => this is what Unity does for Start() etc. too.
// one exception doesn't stop all the other Start() calls!
try
{
comp.OnStartServer();
}
catch (Exception e)
{
Debug.LogError("Exception in OnStartServer:" + e.Message + " " + e.StackTrace);
}
}
}
internal void OnStopServer()
{
foreach (NetworkBehaviour comp in NetworkBehaviours)
{
// an exception in OnStartServer should be caught, so that one
// component's exception doesn't stop all other components from
// being initialized
// => this is what Unity does for Start() etc. too.
// one exception doesn't stop all the other Start() calls!
try
{
comp.OnStopServer();
}
catch (Exception e)
{
Debug.LogError("Exception in OnStopServer:" + e.Message + " " + e.StackTrace);
}
}
}
bool clientStarted;
internal void OnStartClient()
{
if (clientStarted)
return;
clientStarted = true;
isClient = true;
if (LogFilter.Debug) Debug.Log("OnStartClient " + gameObject + " netId:" + netId);
foreach (NetworkBehaviour comp in NetworkBehaviours)
{
// an exception in OnStartClient should be caught, so that one
// component's exception doesn't stop all other components from
// being initialized
// => this is what Unity does for Start() etc. too.
// one exception doesn't stop all the other Start() calls!
try
{
// user implemented startup
comp.OnStartClient();
}
catch (Exception e)
{
Debug.LogError("Exception in OnStartClient:" + e.Message + " " + e.StackTrace);
}
}
}
static NetworkIdentity previousLocalPlayer = null;
internal void OnStartLocalPlayer()
{
if (previousLocalPlayer == this)
return;
previousLocalPlayer = this;
foreach (NetworkBehaviour comp in NetworkBehaviours)
{
// an exception in OnStartLocalPlayer should be caught, so that
// one component's exception doesn't stop all other components
// from being initialized
// => this is what Unity does for Start() etc. too.
// one exception doesn't stop all the other Start() calls!
try
{
comp.OnStartLocalPlayer();
}
catch (Exception e)
{
Debug.LogError("Exception in OnStartLocalPlayer:" + e.Message + " " + e.StackTrace);
}
}
}
bool hadAuthority;
internal void NotifyAuthority()
{
if (!hadAuthority && hasAuthority)
OnStartAuthority();
if (hadAuthority && !hasAuthority)
OnStopAuthority();
hadAuthority = hasAuthority;
}
internal void OnStartAuthority()
{
foreach (NetworkBehaviour comp in NetworkBehaviours)
{
// an exception in OnStartAuthority should be caught, so that one
// component's exception doesn't stop all other components from
// being initialized
// => this is what Unity does for Start() etc. too.
// one exception doesn't stop all the other Start() calls!
try
{
comp.OnStartAuthority();
}
catch (Exception e)
{
Debug.LogError("Exception in OnStartAuthority:" + e.Message + " " + e.StackTrace);
}
}
}
internal void OnStopAuthority()
{
foreach (NetworkBehaviour comp in NetworkBehaviours)
{
// an exception in OnStopAuthority should be caught, so that one
// component's exception doesn't stop all other components from
// being initialized
// => this is what Unity does for Start() etc. too.
// one exception doesn't stop all the other Start() calls!
try
{
comp.OnStopAuthority();
}
catch (Exception e)
{
Debug.LogError("Exception in OnStopAuthority:" + e.Message + " " + e.StackTrace);
}
}
}
internal void OnSetHostVisibility(bool visible)
{
if (visibility != null)
{
try
{
visibility.OnSetHostVisibility(visible);
}
catch (Exception e)
{
Debug.LogError("Exception in OnSetLocalVisibility:" + e.Message + " " + e.StackTrace);
}
}
}
// check if observer can be seen by connection.
// * returns true if seen.
// * returns true if we have no proximity checker, so by default all are
// seen.
internal bool OnCheckObserver(NetworkConnection conn)
{
if (visibility != null)
{
try
{
return visibility.OnCheckObserver(conn);
}
catch (Exception e)
{
Debug.LogError("Exception in OnCheckObserver:" + e.Message + " " + e.StackTrace);
}
}
return true;
}
internal void OnStopClient()
{
foreach (NetworkBehaviour comp in NetworkBehaviours)
{
// an exception in OnNetworkDestroy should be caught, so that
// one component's exception doesn't stop all other components
// from being initialized
// => this is what Unity does for Start() etc. too.
// one exception doesn't stop all the other Start() calls!
try
{
comp.OnStopClient();
}
catch (Exception e)
{
Debug.LogError("Exception in OnNetworkDestroy:" + e.Message + " " + e.StackTrace);
}
isServer = false;
}
}
// vis2k: readstring bug prevention: https://issuetracker.unity3d.com/issues/unet-networkwriter-dot-write-causing-readstring-slash-readbytes-out-of-range-errors-in-clients
// -> OnSerialize writes length,componentData,length,componentData,...
// -> OnDeserialize carefully extracts each data, then deserializes each component with separate readers
// -> it will be impossible to read too many or too few bytes in OnDeserialize
// -> we can properly track down errors
bool OnSerializeSafely(NetworkBehaviour comp, NetworkWriter writer, bool initialState)
{
// write placeholder length bytes
// (jumping back later is WAY faster than allocating a temporary
// writer for the payload, then writing payload.size, payload)
int headerPosition = writer.Position;
writer.WriteInt32(0);
int contentPosition = writer.Position;
// write payload
bool result = false;
try
{
result = comp.OnSerialize(writer, initialState);
}
catch (Exception e)
{
// show a detailed error and let the user know what went wrong
Debug.LogError("OnSerialize failed for: object=" + name + " component=" + comp.GetType() + " sceneId=" + sceneId.ToString("X") + "\n\n" + e);
}
int endPosition = writer.Position;
// fill in length now
writer.Position = headerPosition;
writer.WriteInt32(endPosition - contentPosition);
writer.Position = endPosition;
if (LogFilter.Debug) Debug.Log("OnSerializeSafely written for object=" + comp.name + " component=" + comp.GetType() + " sceneId=" + sceneId.ToString("X") + "header@" + headerPosition + " content@" + contentPosition + " end@" + endPosition + " contentSize=" + (endPosition - contentPosition));
return result;
}
// serialize all components using dirtyComponentsMask
// -> check ownerWritten/observersWritten to know if anything was written
// We pass dirtyComponentsMask into this function so that we can check if any Components are dirty before creating writers
internal void OnSerializeAllSafely(bool initialState, ulong dirtyComponentsMask, NetworkWriter ownerWriter, out int ownerWritten, NetworkWriter observersWriter, out int observersWritten)
{
// clear 'written' variables
ownerWritten = observersWritten = 0;
// dirtyComponentsMask should be changed before tyhis function is called
Debug.Assert(dirtyComponentsMask != 0UL, "OnSerializeAllSafely Should not be given a zero dirtyComponentsMask", this);
// calculate syncMode mask at runtime. this allows users to change
// component.syncMode while the game is running, which can be a huge
// advantage over syncvar-based sync modes. e.g. if a player decides
// to share or not share his inventory, or to go invisible, etc.
//
// (this also lets the TestSynchronizingObjects test pass because
// otherwise if we were to cache it in Awake, then we would call
// GetComponents<NetworkBehaviour> before all the test behaviours
// were added)
ulong syncModeObserversMask = GetSyncModeObserversMask();
// write regular dirty mask for owner,
// writer 'dirty mask & syncMode==Everyone' for everyone else
// (WritePacked64 so we don't write full 8 bytes if we don't have to)
ownerWriter.WritePackedUInt64(dirtyComponentsMask);
observersWriter.WritePackedUInt64(dirtyComponentsMask & syncModeObserversMask);
foreach (NetworkBehaviour comp in NetworkBehaviours)
{
// is this component dirty?
// -> always serialize if initialState so all components are included in spawn packet
// -> note: IsDirty() is false if the component isn't dirty or sendInterval isn't elapsed yet
if (initialState || comp.IsDirty())
{
if (LogFilter.Debug) Debug.Log("OnSerializeAllSafely: " + name + " -> " + comp.GetType() + " initial=" + initialState);
// serialize into ownerWriter first
// (owner always gets everything!)
int startPosition = ownerWriter.Position;
OnSerializeSafely(comp, ownerWriter, initialState);
++ownerWritten;
// copy into observersWriter too if SyncMode.Observers
// -> we copy instead of calling OnSerialize again because
// we don't know what magic the user does in OnSerialize.
// -> it's not guaranteed that calling it twice gets the
// same result
// -> it's not guaranteed that calling it twice doesn't mess
// with the user's OnSerialize timing code etc.
// => so we just copy the result without touching
// OnSerialize again
if (comp.syncMode == SyncMode.Observers)
{
ArraySegment<byte> segment = ownerWriter.ToArraySegment();
int length = ownerWriter.Position - startPosition;
observersWriter.WriteBytes(segment.Array, startPosition, length);
++observersWritten;
}
}
}
}
internal ulong GetDirtyComponentsMask()
{
// loop through all components only once and then write dirty+payload into the writer afterwards
ulong dirtyComponentsMask = 0L;
NetworkBehaviour[] components = NetworkBehaviours;
for (int i = 0; i < components.Length; ++i)
{
NetworkBehaviour comp = components[i];
if (comp.IsDirty())
{
dirtyComponentsMask |= 1UL << i;
}
}
return dirtyComponentsMask;
}
internal ulong GetIntialComponentsMask()
{
// loop through all components only once and then write dirty+payload into the writer afterwards
ulong dirtyComponentsMask = 0UL;
for (int i = 0; i < NetworkBehaviours.Length; ++i)
{
dirtyComponentsMask |= 1UL << i;
}
return dirtyComponentsMask;
}
// a mask that contains all the components with SyncMode.Observers
internal ulong GetSyncModeObserversMask()
{
// loop through all components
ulong mask = 0UL;
NetworkBehaviour[] components = NetworkBehaviours;
for (int i = 0; i < NetworkBehaviours.Length; ++i)
{
NetworkBehaviour comp = components[i];
if (comp.syncMode == SyncMode.Observers)
{
mask |= 1UL << i;
}
}
return mask;
}
void OnDeserializeSafely(NetworkBehaviour comp, NetworkReader reader, bool initialState)
{
// read header as 4 bytes and calculate this chunk's start+end
int contentSize = reader.ReadInt32();
int chunkStart = reader.Position;
int chunkEnd = reader.Position + contentSize;
// call OnDeserialize and wrap it in a try-catch block so there's no
// way to mess up another component's deserialization
try
{
if (LogFilter.Debug) Debug.Log("OnDeserializeSafely: " + comp.name + " component=" + comp.GetType() + " sceneId=" + sceneId.ToString("X") + " length=" + contentSize);
comp.OnDeserialize(reader, initialState);
}
catch (Exception e)
{
// show a detailed error and let the user know what went wrong
Debug.LogError("OnDeserialize failed for: object=" + name + " component=" + comp.GetType() + " sceneId=" + sceneId.ToString("X") + " length=" + contentSize + ". Possible Reasons:\n * Do " + comp.GetType() + "'s OnSerialize and OnDeserialize calls write the same amount of data(" + contentSize + " bytes)? \n * Was there an exception in " + comp.GetType() + "'s OnSerialize/OnDeserialize code?\n * Are the server and client the exact same project?\n * Maybe this OnDeserialize call was meant for another GameObject? The sceneIds can easily get out of sync if the Hierarchy was modified only in the client OR the server. Try rebuilding both.\n\n" + e);
}
// now the reader should be EXACTLY at 'before + size'.
// otherwise the component read too much / too less data.
if (reader.Position != chunkEnd)
{
// warn the user
int bytesRead = reader.Position - chunkStart;
Debug.LogWarning("OnDeserialize was expected to read " + contentSize + " instead of " + bytesRead + " bytes for object:" + name + " component=" + comp.GetType() + " sceneId=" + sceneId.ToString("X") + ". Make sure that OnSerialize and OnDeserialize write/read the same amount of data in all cases.");
// fix the position, so the following components don't all fail
reader.Position = chunkEnd;
}
}
internal void OnDeserializeAllSafely(NetworkReader reader, bool initialState)
{
// read component dirty mask
ulong dirtyComponentsMask = reader.ReadPackedUInt64();
NetworkBehaviour[] components = NetworkBehaviours;
// loop through all components and deserialize the dirty ones
for (int i = 0; i < components.Length; ++i)
{
// is the dirty bit at position 'i' set to 1?
ulong dirtyBit = 1UL << i;
if ((dirtyComponentsMask & dirtyBit) != 0L)
{
OnDeserializeSafely(components[i], reader, initialState);
}
}
}
// helper function to handle SyncEvent/Command/Rpc
void HandleRemoteCall(int componentIndex, int functionHash, MirrorInvokeType invokeType, NetworkReader reader)
{
if (gameObject == null)
{
Debug.LogWarning(invokeType + " [" + functionHash + "] received for deleted object [netId=" + netId + "]");
return;
}
// find the right component to invoke the function on
if (0 <= componentIndex && componentIndex < NetworkBehaviours.Length)
{
NetworkBehaviour invokeComponent = NetworkBehaviours[componentIndex];
if (!invokeComponent.InvokeHandlerDelegate(functionHash, invokeType, reader))
{
Debug.LogError("Found no receiver for incoming " + invokeType + " [" + functionHash + "] on " + gameObject + ", the server and client should have the same NetworkBehaviour instances [netId=" + netId + "].");
}
}
else
{
Debug.LogWarning("Component [" + componentIndex + "] not found for [netId=" + netId + "]");
}