NetworkBehaviour.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679
  1. using System;
  2. using System.Collections.Generic;
  3. using Mirror.RemoteCalls;
  4. using UnityEngine;
  5. namespace Mirror
  6. {
  7. public enum SyncMode { Observers, Owner }
  8. /// <summary>Base class for networked components.</summary>
  9. [AddComponentMenu("")]
  10. [RequireComponent(typeof(NetworkIdentity))]
  11. [HelpURL("https://mirror-networking.gitbook.io/docs/guides/networkbehaviour")]
  12. public abstract class NetworkBehaviour : MonoBehaviour
  13. {
  14. /// <summary>sync mode for OnSerialize</summary>
  15. // hidden because NetworkBehaviourInspector shows it only if has OnSerialize.
  16. [Tooltip("By default synced data is sent from the server to all Observers of the object.\nChange this to Owner to only have the server update the client that has ownership authority for this object")]
  17. [HideInInspector] public SyncMode syncMode = SyncMode.Observers;
  18. /// <summary>sync interval for OnSerialize (in seconds)</summary>
  19. // hidden because NetworkBehaviourInspector shows it only if has OnSerialize.
  20. // [0,2] should be enough. anything >2s is too laggy anyway.
  21. [Tooltip("Time in seconds until next change is synchronized to the client. '0' means send immediately if changed. '0.5' means only send changes every 500ms.\n(This is for state synchronization like SyncVars, SyncLists, OnSerialize. Not for Cmds, Rpcs, etc.)")]
  22. [Range(0, 2)]
  23. [HideInInspector] public float syncInterval = 0.1f;
  24. internal double lastSyncTime;
  25. /// <summary>True if this object is on the server and has been spawned.</summary>
  26. // This is different from NetworkServer.active, which is true if the
  27. // server itself is active rather than this object being active.
  28. public bool isServer => netIdentity.isServer;
  29. /// <summary>True if this object is on the client and has been spawned by the server.</summary>
  30. public bool isClient => netIdentity.isClient;
  31. /// <summary>True if this object is the the client's own local player.</summary>
  32. public bool isLocalPlayer => netIdentity.isLocalPlayer;
  33. /// <summary>True if this object is on the server-only, not host.</summary>
  34. public bool isServerOnly => netIdentity.isServerOnly;
  35. /// <summary>True if this object is on the client-only, not host.</summary>
  36. public bool isClientOnly => netIdentity.isClientOnly;
  37. /// <summary>This returns true if this object is the authoritative version of the object in the distributed network application.</summary>
  38. // keeping this ridiculous summary as a reminder of a time long gone...
  39. public bool hasAuthority => netIdentity.hasAuthority;
  40. /// <summary>The unique network Id of this object (unique at runtime).</summary>
  41. public uint netId => netIdentity.netId;
  42. /// <summary>Client's network connection to the server. This is only valid for player objects on the client.</summary>
  43. public NetworkConnection connectionToServer => netIdentity.connectionToServer;
  44. /// <summary>Server's network connection to the client. This is only valid for player objects on the server.</summary>
  45. public NetworkConnection connectionToClient => netIdentity.connectionToClient;
  46. protected ulong syncVarDirtyBits { get; private set; }
  47. ulong syncVarHookGuard;
  48. // USED BY WEAVER to set syncvars in host mode without deadlocking
  49. protected bool getSyncVarHookGuard(ulong dirtyBit)
  50. {
  51. return (syncVarHookGuard & dirtyBit) != 0UL;
  52. }
  53. // USED BY WEAVER to set syncvars in host mode without deadlocking
  54. protected void setSyncVarHookGuard(ulong dirtyBit, bool value)
  55. {
  56. if (value)
  57. syncVarHookGuard |= dirtyBit;
  58. else
  59. syncVarHookGuard &= ~dirtyBit;
  60. }
  61. // SyncLists, SyncSets, etc.
  62. protected readonly List<SyncObject> syncObjects = new List<SyncObject>();
  63. // NetworkIdentity based values set from NetworkIdentity.Awake(),
  64. // which is way more simple and way faster than trying to figure out
  65. // component index from in here by searching all NetworkComponents.
  66. /// <summary>Returns the NetworkIdentity of this object</summary>
  67. public NetworkIdentity netIdentity { get; internal set; }
  68. /// <summary>Returns the index of the component on this object</summary>
  69. public int ComponentIndex { get; internal set; }
  70. // this gets called in the constructor by the weaver
  71. // for every SyncObject in the component (e.g. SyncLists).
  72. // We collect all of them and we synchronize them with OnSerialize/OnDeserialize
  73. protected void InitSyncObject(SyncObject syncObject)
  74. {
  75. if (syncObject == null)
  76. Debug.LogError("Uninitialized SyncObject. Manually call the constructor on your SyncList, SyncSet or SyncDictionary");
  77. else
  78. syncObjects.Add(syncObject);
  79. }
  80. protected void SendCommandInternal(Type invokeClass, string cmdName, NetworkWriter writer, int channelId, bool requiresAuthority = true)
  81. {
  82. // this was in Weaver before
  83. // NOTE: we could remove this later to allow calling Cmds on Server
  84. // to avoid Wrapper functions. a lot of people requested this.
  85. if (!NetworkClient.active)
  86. {
  87. Debug.LogError($"Command Function {cmdName} called without an active client.");
  88. return;
  89. }
  90. // local players can always send commands, regardless of authority, other objects must have authority.
  91. if (!(!requiresAuthority || isLocalPlayer || hasAuthority))
  92. {
  93. Debug.LogWarning($"Trying to send command for object without authority. {invokeClass}.{cmdName}");
  94. return;
  95. }
  96. // previously we used NetworkClient.readyConnection.
  97. // now we check .ready separately and use .connection instead.
  98. if (!NetworkClient.ready)
  99. {
  100. Debug.LogError("Send command attempted while NetworkClient is not ready.");
  101. return;
  102. }
  103. // IMPORTANT: can't use .connectionToServer here because calling
  104. // a command on other objects is allowed if requireAuthority is
  105. // false. other objects don't have a .connectionToServer.
  106. // => so we always need to use NetworkClient.connection instead.
  107. // => see also: https://github.com/vis2k/Mirror/issues/2629
  108. if (NetworkClient.connection == null)
  109. {
  110. Debug.LogError("Send command attempted with no client running.");
  111. return;
  112. }
  113. // construct the message
  114. CommandMessage message = new CommandMessage
  115. {
  116. netId = netId,
  117. componentIndex = ComponentIndex,
  118. // type+func so Inventory.RpcUse != Equipment.RpcUse
  119. functionHash = RemoteCallHelper.GetMethodHash(invokeClass, cmdName),
  120. // segment to avoid reader allocations
  121. payload = writer.ToArraySegment()
  122. };
  123. // IMPORTANT: can't use .connectionToServer here because calling
  124. // a command on other objects is allowed if requireAuthority is
  125. // false. other objects don't have a .connectionToServer.
  126. // => so we always need to use NetworkClient.connection instead.
  127. // => see also: https://github.com/vis2k/Mirror/issues/2629
  128. NetworkClient.connection.Send(message, channelId);
  129. }
  130. protected void SendRPCInternal(Type invokeClass, string rpcName, NetworkWriter writer, int channelId, bool includeOwner)
  131. {
  132. // this was in Weaver before
  133. if (!NetworkServer.active)
  134. {
  135. Debug.LogError("RPC Function " + rpcName + " called on Client.");
  136. return;
  137. }
  138. // This cannot use NetworkServer.active, as that is not specific to this object.
  139. if (!isServer)
  140. {
  141. Debug.LogWarning("ClientRpc " + rpcName + " called on un-spawned object: " + name);
  142. return;
  143. }
  144. // construct the message
  145. RpcMessage message = new RpcMessage
  146. {
  147. netId = netId,
  148. componentIndex = ComponentIndex,
  149. // type+func so Inventory.RpcUse != Equipment.RpcUse
  150. functionHash = RemoteCallHelper.GetMethodHash(invokeClass, rpcName),
  151. // segment to avoid reader allocations
  152. payload = writer.ToArraySegment()
  153. };
  154. NetworkServer.SendToReady(netIdentity, message, includeOwner, channelId);
  155. }
  156. protected void SendTargetRPCInternal(NetworkConnection conn, Type invokeClass, string rpcName, NetworkWriter writer, int channelId)
  157. {
  158. if (!NetworkServer.active)
  159. {
  160. Debug.LogError($"TargetRPC {rpcName} called when server not active");
  161. return;
  162. }
  163. if (!isServer)
  164. {
  165. Debug.LogWarning($"TargetRpc {rpcName} called on {name} but that object has not been spawned or has been unspawned");
  166. return;
  167. }
  168. // connection parameter is optional. assign if null.
  169. if (conn is null)
  170. {
  171. conn = connectionToClient;
  172. }
  173. // if still null
  174. if (conn is null)
  175. {
  176. Debug.LogError($"TargetRPC {rpcName} was given a null connection, make sure the object has an owner or you pass in the target connection");
  177. return;
  178. }
  179. if (!(conn is NetworkConnectionToClient))
  180. {
  181. Debug.LogError($"TargetRPC {rpcName} requires a NetworkConnectionToClient but was given {conn.GetType().Name}");
  182. return;
  183. }
  184. // construct the message
  185. RpcMessage message = new RpcMessage
  186. {
  187. netId = netId,
  188. componentIndex = ComponentIndex,
  189. // type+func so Inventory.RpcUse != Equipment.RpcUse
  190. functionHash = RemoteCallHelper.GetMethodHash(invokeClass, rpcName),
  191. // segment to avoid reader allocations
  192. payload = writer.ToArraySegment()
  193. };
  194. conn.Send(message, channelId);
  195. }
  196. // helper function for [SyncVar] GameObjects.
  197. // IMPORTANT: keep as 'protected', not 'internal', otherwise Weaver
  198. // can't resolve it
  199. // TODO make this static and adjust weaver to find it
  200. protected bool SyncVarGameObjectEqual(GameObject newGameObject, uint netIdField)
  201. {
  202. uint newNetId = 0;
  203. if (newGameObject != null)
  204. {
  205. NetworkIdentity identity = newGameObject.GetComponent<NetworkIdentity>();
  206. if (identity != null)
  207. {
  208. newNetId = identity.netId;
  209. if (newNetId == 0)
  210. {
  211. Debug.LogWarning("SetSyncVarGameObject GameObject " + newGameObject + " has a zero netId. Maybe it is not spawned yet?");
  212. }
  213. }
  214. }
  215. return newNetId == netIdField;
  216. }
  217. // helper function for [SyncVar] GameObjects.
  218. protected void SetSyncVarGameObject(GameObject newGameObject, ref GameObject gameObjectField, ulong dirtyBit, ref uint netIdField)
  219. {
  220. if (getSyncVarHookGuard(dirtyBit))
  221. return;
  222. uint newNetId = 0;
  223. if (newGameObject != null)
  224. {
  225. NetworkIdentity identity = newGameObject.GetComponent<NetworkIdentity>();
  226. if (identity != null)
  227. {
  228. newNetId = identity.netId;
  229. if (newNetId == 0)
  230. {
  231. Debug.LogWarning("SetSyncVarGameObject GameObject " + newGameObject + " has a zero netId. Maybe it is not spawned yet?");
  232. }
  233. }
  234. }
  235. // Debug.Log("SetSyncVar GameObject " + GetType().Name + " bit [" + dirtyBit + "] netfieldId:" + netIdField + "->" + newNetId);
  236. SetDirtyBit(dirtyBit);
  237. // assign new one on the server, and in case we ever need it on client too
  238. gameObjectField = newGameObject;
  239. netIdField = newNetId;
  240. }
  241. // helper function for [SyncVar] GameObjects.
  242. // -> ref GameObject as second argument makes OnDeserialize processing easier
  243. protected GameObject GetSyncVarGameObject(uint netId, ref GameObject gameObjectField)
  244. {
  245. // server always uses the field
  246. if (isServer)
  247. {
  248. return gameObjectField;
  249. }
  250. // client always looks up based on netId because objects might get in and out of range
  251. // over and over again, which shouldn't null them forever
  252. if (NetworkIdentity.spawned.TryGetValue(netId, out NetworkIdentity identity) && identity != null)
  253. return gameObjectField = identity.gameObject;
  254. return null;
  255. }
  256. // helper function for [SyncVar] NetworkIdentities.
  257. // IMPORTANT: keep as 'protected', not 'internal', otherwise Weaver
  258. // can't resolve it
  259. protected bool SyncVarNetworkIdentityEqual(NetworkIdentity newIdentity, uint netIdField)
  260. {
  261. uint newNetId = 0;
  262. if (newIdentity != null)
  263. {
  264. newNetId = newIdentity.netId;
  265. if (newNetId == 0)
  266. {
  267. Debug.LogWarning("SetSyncVarNetworkIdentity NetworkIdentity " + newIdentity + " has a zero netId. Maybe it is not spawned yet?");
  268. }
  269. }
  270. // netId changed?
  271. return newNetId == netIdField;
  272. }
  273. // helper function for [SyncVar] NetworkIdentities.
  274. protected void SetSyncVarNetworkIdentity(NetworkIdentity newIdentity, ref NetworkIdentity identityField, ulong dirtyBit, ref uint netIdField)
  275. {
  276. if (getSyncVarHookGuard(dirtyBit))
  277. return;
  278. uint newNetId = 0;
  279. if (newIdentity != null)
  280. {
  281. newNetId = newIdentity.netId;
  282. if (newNetId == 0)
  283. {
  284. Debug.LogWarning("SetSyncVarNetworkIdentity NetworkIdentity " + newIdentity + " has a zero netId. Maybe it is not spawned yet?");
  285. }
  286. }
  287. // Debug.Log("SetSyncVarNetworkIdentity NetworkIdentity " + GetType().Name + " bit [" + dirtyBit + "] netIdField:" + netIdField + "->" + newNetId);
  288. SetDirtyBit(dirtyBit);
  289. netIdField = newNetId;
  290. // assign new one on the server, and in case we ever need it on client too
  291. identityField = newIdentity;
  292. }
  293. // helper function for [SyncVar] NetworkIdentities.
  294. // -> ref GameObject as second argument makes OnDeserialize processing easier
  295. protected NetworkIdentity GetSyncVarNetworkIdentity(uint netId, ref NetworkIdentity identityField)
  296. {
  297. // server always uses the field
  298. if (isServer)
  299. {
  300. return identityField;
  301. }
  302. // client always looks up based on netId because objects might get in and out of range
  303. // over and over again, which shouldn't null them forever
  304. NetworkIdentity.spawned.TryGetValue(netId, out identityField);
  305. return identityField;
  306. }
  307. protected bool SyncVarNetworkBehaviourEqual<T>(T newBehaviour, NetworkBehaviourSyncVar syncField) where T : NetworkBehaviour
  308. {
  309. uint newNetId = 0;
  310. int newComponentIndex = 0;
  311. if (newBehaviour != null)
  312. {
  313. newNetId = newBehaviour.netId;
  314. newComponentIndex = newBehaviour.ComponentIndex;
  315. if (newNetId == 0)
  316. {
  317. Debug.LogWarning("SetSyncVarNetworkIdentity NetworkIdentity " + newBehaviour + " has a zero netId. Maybe it is not spawned yet?");
  318. }
  319. }
  320. // netId changed?
  321. return syncField.Equals(newNetId, newComponentIndex);
  322. }
  323. // helper function for [SyncVar] NetworkIdentities.
  324. protected void SetSyncVarNetworkBehaviour<T>(T newBehaviour, ref T behaviourField, ulong dirtyBit, ref NetworkBehaviourSyncVar syncField) where T : NetworkBehaviour
  325. {
  326. if (getSyncVarHookGuard(dirtyBit))
  327. return;
  328. uint newNetId = 0;
  329. int componentIndex = 0;
  330. if (newBehaviour != null)
  331. {
  332. newNetId = newBehaviour.netId;
  333. componentIndex = newBehaviour.ComponentIndex;
  334. if (newNetId == 0)
  335. {
  336. Debug.LogWarning($"{nameof(SetSyncVarNetworkBehaviour)} NetworkIdentity " + newBehaviour + " has a zero netId. Maybe it is not spawned yet?");
  337. }
  338. }
  339. syncField = new NetworkBehaviourSyncVar(newNetId, componentIndex);
  340. SetDirtyBit(dirtyBit);
  341. // assign new one on the server, and in case we ever need it on client too
  342. behaviourField = newBehaviour;
  343. // Debug.Log($"SetSyncVarNetworkBehaviour NetworkIdentity {GetType().Name} bit [{dirtyBit}] netIdField:{oldField}->{syncField}");
  344. }
  345. // helper function for [SyncVar] NetworkIdentities.
  346. // -> ref GameObject as second argument makes OnDeserialize processing easier
  347. protected T GetSyncVarNetworkBehaviour<T>(NetworkBehaviourSyncVar syncNetBehaviour, ref T behaviourField) where T : NetworkBehaviour
  348. {
  349. // server always uses the field
  350. if (isServer)
  351. {
  352. return behaviourField;
  353. }
  354. // client always looks up based on netId because objects might get in and out of range
  355. // over and over again, which shouldn't null them forever
  356. if (!NetworkIdentity.spawned.TryGetValue(syncNetBehaviour.netId, out NetworkIdentity identity))
  357. {
  358. return null;
  359. }
  360. behaviourField = identity.NetworkBehaviours[syncNetBehaviour.componentIndex] as T;
  361. return behaviourField;
  362. }
  363. // backing field for sync NetworkBehaviour
  364. public struct NetworkBehaviourSyncVar : IEquatable<NetworkBehaviourSyncVar>
  365. {
  366. public uint netId;
  367. // limited to 255 behaviours per identity
  368. public byte componentIndex;
  369. public NetworkBehaviourSyncVar(uint netId, int componentIndex) : this()
  370. {
  371. this.netId = netId;
  372. this.componentIndex = (byte)componentIndex;
  373. }
  374. public bool Equals(NetworkBehaviourSyncVar other)
  375. {
  376. return other.netId == netId && other.componentIndex == componentIndex;
  377. }
  378. public bool Equals(uint netId, int componentIndex)
  379. {
  380. return this.netId == netId && this.componentIndex == componentIndex;
  381. }
  382. public override string ToString()
  383. {
  384. return $"[netId:{netId} compIndex:{componentIndex}]";
  385. }
  386. }
  387. protected bool SyncVarEqual<T>(T value, ref T fieldValue)
  388. {
  389. // newly initialized or changed value?
  390. return EqualityComparer<T>.Default.Equals(value, fieldValue);
  391. }
  392. protected void SetSyncVar<T>(T value, ref T fieldValue, ulong dirtyBit)
  393. {
  394. // Debug.Log("SetSyncVar " + GetType().Name + " bit [" + dirtyBit + "] " + fieldValue + "->" + value);
  395. SetDirtyBit(dirtyBit);
  396. fieldValue = value;
  397. }
  398. /// <summary>Set as dirty so that it's synced to clients again.</summary>
  399. // these are masks, not bit numbers, ie. 0x004 not 2
  400. public void SetDirtyBit(ulong dirtyBit)
  401. {
  402. syncVarDirtyBits |= dirtyBit;
  403. }
  404. /// <summary>Clears all the dirty bits that were set by SetDirtyBits()</summary>
  405. // automatically invoked when an update is sent for this object, but can
  406. // be called manually as well.
  407. public void ClearAllDirtyBits()
  408. {
  409. lastSyncTime = NetworkTime.localTime;
  410. syncVarDirtyBits = 0L;
  411. // flush all unsynchronized changes in syncobjects
  412. // note: don't use List.ForEach here, this is a hot path
  413. // List.ForEach: 432b/frame
  414. // for: 231b/frame
  415. for (int i = 0; i < syncObjects.Count; ++i)
  416. {
  417. syncObjects[i].Flush();
  418. }
  419. }
  420. bool AnySyncObjectDirty()
  421. {
  422. // note: don't use Linq here. 1200 networked objects:
  423. // Linq: 187KB GC/frame;, 2.66ms time
  424. // for: 8KB GC/frame; 1.28ms time
  425. for (int i = 0; i < syncObjects.Count; ++i)
  426. {
  427. if (syncObjects[i].IsDirty)
  428. {
  429. return true;
  430. }
  431. }
  432. return false;
  433. }
  434. // true if syncInterval elapsed and any SyncVar or SyncObject is dirty
  435. public bool IsDirty()
  436. {
  437. if (NetworkTime.localTime - lastSyncTime >= syncInterval)
  438. {
  439. return syncVarDirtyBits != 0L || AnySyncObjectDirty();
  440. }
  441. return false;
  442. }
  443. /// <summary>Override to do custom serialization (instead of SyncVars/SyncLists). Use OnDeserialize too.</summary>
  444. // if a class has syncvars, then OnSerialize/OnDeserialize are added
  445. // automatically.
  446. //
  447. // initialState is true for full spawns, false for delta syncs.
  448. // note: SyncVar hooks are only called when inital=false
  449. public virtual bool OnSerialize(NetworkWriter writer, bool initialState)
  450. {
  451. bool objectWritten = false;
  452. // if initialState: write all SyncVars.
  453. // otherwise write dirtyBits+dirty SyncVars
  454. if (initialState)
  455. {
  456. objectWritten = SerializeObjectsAll(writer);
  457. }
  458. else
  459. {
  460. objectWritten = SerializeObjectsDelta(writer);
  461. }
  462. bool syncVarWritten = SerializeSyncVars(writer, initialState);
  463. return objectWritten || syncVarWritten;
  464. }
  465. /// <summary>Override to do custom deserialization (instead of SyncVars/SyncLists). Use OnSerialize too.</summary>
  466. public virtual void OnDeserialize(NetworkReader reader, bool initialState)
  467. {
  468. if (initialState)
  469. {
  470. DeSerializeObjectsAll(reader);
  471. }
  472. else
  473. {
  474. DeSerializeObjectsDelta(reader);
  475. }
  476. DeserializeSyncVars(reader, initialState);
  477. }
  478. // USED BY WEAVER
  479. protected virtual bool SerializeSyncVars(NetworkWriter writer, bool initialState)
  480. {
  481. return false;
  482. // SyncVar are written here in subclass
  483. // if initialState
  484. // write all SyncVars
  485. // else
  486. // write syncVarDirtyBits
  487. // write dirty SyncVars
  488. }
  489. // USED BY WEAVER
  490. protected virtual void DeserializeSyncVars(NetworkReader reader, bool initialState)
  491. {
  492. // SyncVars are read here in subclass
  493. // if initialState
  494. // read all SyncVars
  495. // else
  496. // read syncVarDirtyBits
  497. // read dirty SyncVars
  498. }
  499. internal ulong DirtyObjectBits()
  500. {
  501. ulong dirtyObjects = 0;
  502. for (int i = 0; i < syncObjects.Count; i++)
  503. {
  504. SyncObject syncObject = syncObjects[i];
  505. if (syncObject.IsDirty)
  506. {
  507. dirtyObjects |= 1UL << i;
  508. }
  509. }
  510. return dirtyObjects;
  511. }
  512. public bool SerializeObjectsAll(NetworkWriter writer)
  513. {
  514. bool dirty = false;
  515. for (int i = 0; i < syncObjects.Count; i++)
  516. {
  517. SyncObject syncObject = syncObjects[i];
  518. syncObject.OnSerializeAll(writer);
  519. dirty = true;
  520. }
  521. return dirty;
  522. }
  523. public bool SerializeObjectsDelta(NetworkWriter writer)
  524. {
  525. bool dirty = false;
  526. // write the mask
  527. writer.WriteULong(DirtyObjectBits());
  528. // serializable objects, such as synclists
  529. for (int i = 0; i < syncObjects.Count; i++)
  530. {
  531. SyncObject syncObject = syncObjects[i];
  532. if (syncObject.IsDirty)
  533. {
  534. syncObject.OnSerializeDelta(writer);
  535. dirty = true;
  536. }
  537. }
  538. return dirty;
  539. }
  540. internal void DeSerializeObjectsAll(NetworkReader reader)
  541. {
  542. for (int i = 0; i < syncObjects.Count; i++)
  543. {
  544. SyncObject syncObject = syncObjects[i];
  545. syncObject.OnDeserializeAll(reader);
  546. }
  547. }
  548. internal void DeSerializeObjectsDelta(NetworkReader reader)
  549. {
  550. ulong dirty = reader.ReadULong();
  551. for (int i = 0; i < syncObjects.Count; i++)
  552. {
  553. SyncObject syncObject = syncObjects[i];
  554. if ((dirty & (1UL << i)) != 0)
  555. {
  556. syncObject.OnDeserializeDelta(reader);
  557. }
  558. }
  559. }
  560. internal void ResetSyncObjects()
  561. {
  562. foreach (SyncObject syncObject in syncObjects)
  563. {
  564. syncObject.Reset();
  565. }
  566. }
  567. /// <summary>Like Start(), but only called on server and host.</summary>
  568. public virtual void OnStartServer() {}
  569. /// <summary>Stop event, only called on server and host.</summary>
  570. public virtual void OnStopServer() {}
  571. /// <summary>Like Start(), but only called on client and host.</summary>
  572. public virtual void OnStartClient() {}
  573. /// <summary>Stop event, only called on client and host.</summary>
  574. public virtual void OnStopClient() {}
  575. /// <summary>Like Start(), but only called on client and host for the local player object.</summary>
  576. public virtual void OnStartLocalPlayer() {}
  577. /// <summary>Like Start(), but only called for objects the client has authority over.</summary>
  578. public virtual void OnStartAuthority() {}
  579. /// <summary>Stop event, only called for objects the client has authority over.</summary>
  580. public virtual void OnStopAuthority() {}
  581. }
  582. }