PunClasses.cs 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974
  1. // ----------------------------------------------------------------------------
  2. // <copyright file="PunClasses.cs" company="Exit Games GmbH">
  3. // PhotonNetwork Framework for Unity - Copyright (C) 2018 Exit Games GmbH
  4. // </copyright>
  5. // <summary>
  6. // Wraps up smaller classes that don't need their own file.
  7. // </summary>
  8. // <author>developer@exitgames.com</author>
  9. // ----------------------------------------------------------------------------
  10. #pragma warning disable 1587
  11. /// \defgroup publicApi Public API
  12. /// \brief Groups the most important classes that you need to understand early on.
  13. ///
  14. /// \defgroup optionalGui Optional Gui Elements
  15. /// \brief Useful GUI elements for PUN.
  16. ///
  17. /// \defgroup callbacks Callbacks
  18. /// \brief Callback Interfaces
  19. #pragma warning restore 1587
  20. namespace Photon.Pun
  21. {
  22. using System;
  23. using System.Collections.Generic;
  24. using System.Reflection;
  25. using ExitGames.Client.Photon;
  26. using UnityEngine;
  27. using UnityEngine.SceneManagement;
  28. using Photon.Realtime;
  29. using SupportClassPun = ExitGames.Client.Photon.SupportClass;
  30. /// <summary>Replacement for RPC attribute with different name. Used to flag methods as remote-callable.</summary>
  31. public class PunRPC : Attribute
  32. {
  33. }
  34. /// <summary>
  35. /// This class adds the property photonView, while logging a warning when your game still uses the networkView.
  36. /// </summary>
  37. public class MonoBehaviourPun : MonoBehaviour
  38. {
  39. /// <summary>Cache field for the PhotonView on this GameObject.</summary>
  40. private PhotonView pvCache;
  41. /// <summary>A cached reference to a PhotonView on this GameObject.</summary>
  42. /// <remarks>
  43. /// If you intend to work with a PhotonView in a script, it's usually easier to write this.photonView.
  44. ///
  45. /// If you intend to remove the PhotonView component from the GameObject but keep this Photon.MonoBehaviour,
  46. /// avoid this reference or modify this code to use PhotonView.Get(obj) instead.
  47. /// </remarks>
  48. public PhotonView photonView
  49. {
  50. get
  51. {
  52. #if UNITY_EDITOR
  53. // In the editor we want to avoid caching this at design time, so changes in PV structure appear immediately.
  54. if (!Application.isPlaying || this.pvCache == null)
  55. {
  56. this.pvCache = PhotonView.Get(this);
  57. }
  58. #else
  59. if (this.pvCache == null)
  60. {
  61. this.pvCache = PhotonView.Get(this);
  62. }
  63. #endif
  64. return this.pvCache;
  65. }
  66. }
  67. //#if UNITY_EDITOR
  68. //protected virtual void Reset()
  69. //{
  70. // this.pvCache = this.transform.GetParentComponent<PhotonView>();
  71. // if (this.pvCache == null)
  72. // {
  73. // Debug.LogWarning(this.GetType().Name + " requires a PhotonView. No PhotonView was found, so one is being added to GameObject '" + this.transform.root.name + "'");
  74. // this.pvCache = this.transform.root.gameObject.AddComponent<PhotonView>();
  75. // }
  76. //}
  77. //#endif
  78. }
  79. /// <summary>
  80. /// This class provides a .photonView and all callbacks/events that PUN can call. Override the events/methods you want to use.
  81. /// </summary>
  82. /// <remarks>
  83. /// By extending this class, you can implement individual methods as override.
  84. ///
  85. /// Do not add <b>new</b> <code>MonoBehaviour.OnEnable</code> or <code>MonoBehaviour.OnDisable</code>
  86. /// Instead, you should override those and call <code>base.OnEnable</code> and <code>base.OnDisable</code>.
  87. ///
  88. /// Visual Studio and MonoDevelop should provide the list of methods when you begin typing "override".
  89. /// <b>Your implementation does not have to call "base.method()".</b>
  90. ///
  91. /// This class implements all callback interfaces and extends <see cref="Photon.Pun.MonoBehaviourPun"/>.
  92. /// </remarks>
  93. /// \ingroup callbacks
  94. // the documentation for the interface methods becomes inherited when Doxygen builds it.
  95. public class MonoBehaviourPunCallbacks : MonoBehaviourPun, IConnectionCallbacks , IMatchmakingCallbacks , IInRoomCallbacks, ILobbyCallbacks, IWebRpcCallback, IErrorInfoCallback
  96. {
  97. public virtual void OnEnable()
  98. {
  99. PhotonNetwork.AddCallbackTarget(this);
  100. }
  101. public virtual void OnDisable()
  102. {
  103. PhotonNetwork.RemoveCallbackTarget(this);
  104. }
  105. /// <summary>
  106. /// Called to signal that the raw connection got established but before the client can call operation on the server.
  107. /// </summary>
  108. /// <remarks>
  109. /// After the (low level transport) connection is established, the client will automatically send
  110. /// the Authentication operation, which needs to get a response before the client can call other operations.
  111. ///
  112. /// Your logic should wait for either: OnRegionListReceived or OnConnectedToMaster.
  113. ///
  114. /// This callback is useful to detect if the server can be reached at all (technically).
  115. /// Most often, it's enough to implement OnDisconnected().
  116. ///
  117. /// This is not called for transitions from the masterserver to game servers.
  118. /// </remarks>
  119. public virtual void OnConnected()
  120. {
  121. }
  122. /// <summary>
  123. /// Called when the local user/client left a room, so the game's logic can clean up it's internal state.
  124. /// </summary>
  125. /// <remarks>
  126. /// When leaving a room, the LoadBalancingClient will disconnect the Game Server and connect to the Master Server.
  127. /// This wraps up multiple internal actions.
  128. ///
  129. /// Wait for the callback OnConnectedToMaster, before you use lobbies and join or create rooms.
  130. /// </remarks>
  131. public virtual void OnLeftRoom()
  132. {
  133. }
  134. /// <summary>
  135. /// Called after switching to a new MasterClient when the current one leaves.
  136. /// </summary>
  137. /// <remarks>
  138. /// This is not called when this client enters a room.
  139. /// The former MasterClient is still in the player list when this method get called.
  140. /// </remarks>
  141. public virtual void OnMasterClientSwitched(Player newMasterClient)
  142. {
  143. }
  144. /// <summary>
  145. /// Called when the server couldn't create a room (OpCreateRoom failed).
  146. /// </summary>
  147. /// <remarks>
  148. /// The most common cause to fail creating a room, is when a title relies on fixed room-names and the room already exists.
  149. /// </remarks>
  150. /// <param name="returnCode">Operation ReturnCode from the server.</param>
  151. /// <param name="message">Debug message for the error.</param>
  152. public virtual void OnCreateRoomFailed(short returnCode, string message)
  153. {
  154. }
  155. /// <summary>
  156. /// Called when a previous OpJoinRoom call failed on the server.
  157. /// </summary>
  158. /// <remarks>
  159. /// The most common causes are that a room is full or does not exist (due to someone else being faster or closing the room).
  160. /// </remarks>
  161. /// <param name="returnCode">Operation ReturnCode from the server.</param>
  162. /// <param name="message">Debug message for the error.</param>
  163. public virtual void OnJoinRoomFailed(short returnCode, string message)
  164. {
  165. }
  166. /// <summary>
  167. /// Called when this client created a room and entered it. OnJoinedRoom() will be called as well.
  168. /// </summary>
  169. /// <remarks>
  170. /// This callback is only called on the client which created a room (see OpCreateRoom).
  171. ///
  172. /// As any client might close (or drop connection) anytime, there is a chance that the
  173. /// creator of a room does not execute OnCreatedRoom.
  174. ///
  175. /// If you need specific room properties or a "start signal", implement OnMasterClientSwitched()
  176. /// and make each new MasterClient check the room's state.
  177. /// </remarks>
  178. public virtual void OnCreatedRoom()
  179. {
  180. }
  181. /// <summary>
  182. /// Called on entering a lobby on the Master Server. The actual room-list updates will call OnRoomListUpdate.
  183. /// </summary>
  184. /// <remarks>
  185. /// While in the lobby, the roomlist is automatically updated in fixed intervals (which you can't modify in the public cloud).
  186. /// The room list gets available via OnRoomListUpdate.
  187. /// </remarks>
  188. public virtual void OnJoinedLobby()
  189. {
  190. }
  191. /// <summary>
  192. /// Called after leaving a lobby.
  193. /// </summary>
  194. /// <remarks>
  195. /// When you leave a lobby, [OpCreateRoom](@ref OpCreateRoom) and [OpJoinRandomRoom](@ref OpJoinRandomRoom)
  196. /// automatically refer to the default lobby.
  197. /// </remarks>
  198. public virtual void OnLeftLobby()
  199. {
  200. }
  201. /// <summary>
  202. /// Called after disconnecting from the Photon server. It could be a failure or intentional
  203. /// </summary>
  204. /// <remarks>
  205. /// The reason for this disconnect is provided as DisconnectCause.
  206. /// </remarks>
  207. public virtual void OnDisconnected(DisconnectCause cause)
  208. {
  209. }
  210. /// <summary>
  211. /// Called when the Name Server provided a list of regions for your title.
  212. /// </summary>
  213. /// <remarks>Check the RegionHandler class description, to make use of the provided values.</remarks>
  214. /// <param name="regionHandler">The currently used RegionHandler.</param>
  215. public virtual void OnRegionListReceived(RegionHandler regionHandler)
  216. {
  217. }
  218. /// <summary>
  219. /// Called for any update of the room-listing while in a lobby (InLobby) on the Master Server.
  220. /// </summary>
  221. /// <remarks>
  222. /// Each item is a RoomInfo which might include custom properties (provided you defined those as lobby-listed when creating a room).
  223. /// Not all types of lobbies provide a listing of rooms to the client. Some are silent and specialized for server-side matchmaking.
  224. /// </remarks>
  225. public virtual void OnRoomListUpdate(List<RoomInfo> roomList)
  226. {
  227. }
  228. /// <summary>
  229. /// Called when the LoadBalancingClient entered a room, no matter if this client created it or simply joined.
  230. /// </summary>
  231. /// <remarks>
  232. /// When this is called, you can access the existing players in Room.Players, their custom properties and Room.CustomProperties.
  233. ///
  234. /// In this callback, you could create player objects. For example in Unity, instantiate a prefab for the player.
  235. ///
  236. /// If you want a match to be started "actively", enable the user to signal "ready" (using OpRaiseEvent or a Custom Property).
  237. /// </remarks>
  238. public virtual void OnJoinedRoom()
  239. {
  240. }
  241. /// <summary>
  242. /// Called when a remote player entered the room. This Player is already added to the playerlist.
  243. /// </summary>
  244. /// <remarks>
  245. /// If your game starts with a certain number of players, this callback can be useful to check the
  246. /// Room.playerCount and find out if you can start.
  247. /// </remarks>
  248. public virtual void OnPlayerEnteredRoom(Player newPlayer)
  249. {
  250. }
  251. /// <summary>
  252. /// Called when a remote player left the room or became inactive. Check otherPlayer.IsInactive.
  253. /// </summary>
  254. /// <remarks>
  255. /// If another player leaves the room or if the server detects a lost connection, this callback will
  256. /// be used to notify your game logic.
  257. ///
  258. /// Depending on the room's setup, players may become inactive, which means they may return and retake
  259. /// their spot in the room. In such cases, the Player stays in the Room.Players dictionary.
  260. ///
  261. /// If the player is not just inactive, it gets removed from the Room.Players dictionary, before
  262. /// the callback is called.
  263. /// </remarks>
  264. public virtual void OnPlayerLeftRoom(Player otherPlayer)
  265. {
  266. }
  267. /// <summary>
  268. /// Called when a previous OpJoinRandom call failed on the server.
  269. /// </summary>
  270. /// <remarks>
  271. /// The most common causes are that a room is full or does not exist (due to someone else being faster or closing the room).
  272. ///
  273. /// When using multiple lobbies (via OpJoinLobby or a TypedLobby parameter), another lobby might have more/fitting rooms.<br/>
  274. /// </remarks>
  275. /// <param name="returnCode">Operation ReturnCode from the server.</param>
  276. /// <param name="message">Debug message for the error.</param>
  277. public virtual void OnJoinRandomFailed(short returnCode, string message)
  278. {
  279. }
  280. /// <summary>
  281. /// Called when the client is connected to the Master Server and ready for matchmaking and other tasks.
  282. /// </summary>
  283. /// <remarks>
  284. /// The list of available rooms won't become available unless you join a lobby via LoadBalancingClient.OpJoinLobby.
  285. /// You can join rooms and create them even without being in a lobby. The default lobby is used in that case.
  286. /// </remarks>
  287. public virtual void OnConnectedToMaster()
  288. {
  289. }
  290. /// <summary>
  291. /// Called when a room's custom properties changed. The propertiesThatChanged contains all that was set via Room.SetCustomProperties.
  292. /// </summary>
  293. /// <remarks>
  294. /// Since v1.25 this method has one parameter: Hashtable propertiesThatChanged.<br/>
  295. /// Changing properties must be done by Room.SetCustomProperties, which causes this callback locally, too.
  296. /// </remarks>
  297. /// <param name="propertiesThatChanged"></param>
  298. public virtual void OnRoomPropertiesUpdate(Hashtable propertiesThatChanged)
  299. {
  300. }
  301. /// <summary>
  302. /// Called when custom player-properties are changed. Player and the changed properties are passed as object[].
  303. /// </summary>
  304. /// <remarks>
  305. /// Changing properties must be done by Player.SetCustomProperties, which causes this callback locally, too.
  306. /// </remarks>
  307. ///
  308. /// <param name="targetPlayer">Contains Player that changed.</param>
  309. /// <param name="changedProps">Contains the properties that changed.</param>
  310. public virtual void OnPlayerPropertiesUpdate(Player targetPlayer, Hashtable changedProps)
  311. {
  312. }
  313. /// <summary>
  314. /// Called when the server sent the response to a FindFriends request.
  315. /// </summary>
  316. /// <remarks>
  317. /// After calling OpFindFriends, the Master Server will cache the friend list and send updates to the friend
  318. /// list. The friends includes the name, userId, online state and the room (if any) for each requested user/friend.
  319. ///
  320. /// Use the friendList to update your UI and store it, if the UI should highlight changes.
  321. /// </remarks>
  322. public virtual void OnFriendListUpdate(List<FriendInfo> friendList)
  323. {
  324. }
  325. /// <summary>
  326. /// Called when your Custom Authentication service responds with additional data.
  327. /// </summary>
  328. /// <remarks>
  329. /// Custom Authentication services can include some custom data in their response.
  330. /// When present, that data is made available in this callback as Dictionary.
  331. /// While the keys of your data have to be strings, the values can be either string or a number (in Json).
  332. /// You need to make extra sure, that the value type is the one you expect. Numbers become (currently) int64.
  333. ///
  334. /// Example: void OnCustomAuthenticationResponse(Dictionary&lt;string, object&gt; data) { ... }
  335. /// </remarks>
  336. /// <see cref="https://doc.photonengine.com/en-us/realtime/current/reference/custom-authentication"/>
  337. public virtual void OnCustomAuthenticationResponse(Dictionary<string, object> data)
  338. {
  339. }
  340. /// <summary>
  341. /// Called when the custom authentication failed. Followed by disconnect!
  342. /// </summary>
  343. /// <remarks>
  344. /// Custom Authentication can fail due to user-input, bad tokens/secrets.
  345. /// If authentication is successful, this method is not called. Implement OnJoinedLobby() or OnConnectedToMaster() (as usual).
  346. ///
  347. /// During development of a game, it might also fail due to wrong configuration on the server side.
  348. /// In those cases, logging the debugMessage is very important.
  349. ///
  350. /// Unless you setup a custom authentication service for your app (in the [Dashboard](https://dashboard.photonengine.com)),
  351. /// this won't be called!
  352. /// </remarks>
  353. /// <param name="debugMessage">Contains a debug message why authentication failed. This has to be fixed during development.</param>
  354. public virtual void OnCustomAuthenticationFailed (string debugMessage)
  355. {
  356. }
  357. //TODO: Check if this needs to be implemented
  358. // in: IOptionalInfoCallbacks
  359. public virtual void OnWebRpcResponse(OperationResponse response)
  360. {
  361. }
  362. //TODO: Check if this needs to be implemented
  363. // in: IOptionalInfoCallbacks
  364. public virtual void OnLobbyStatisticsUpdate(List<TypedLobbyInfo> lobbyStatistics)
  365. {
  366. }
  367. /// <summary>
  368. /// Called when the client receives an event from the server indicating that an error happened there.
  369. /// </summary>
  370. /// <remarks>
  371. /// In most cases this could be either:
  372. /// 1. an error from webhooks plugin (if HasErrorInfo is enabled), read more here:
  373. /// https://doc.photonengine.com/en-us/realtime/current/gameplay/web-extensions/webhooks#options
  374. /// 2. an error sent from a custom server plugin via PluginHost.BroadcastErrorInfoEvent, see example here:
  375. /// https://doc.photonengine.com/en-us/server/current/plugins/manual#handling_http_response
  376. /// 3. an error sent from the server, for example, when the limit of cached events has been exceeded in the room
  377. /// (all clients will be disconnected and the room will be closed in this case)
  378. /// read more here: https://doc.photonengine.com/en-us/realtime/current/gameplay/cached-events#special_considerations
  379. /// </remarks>
  380. /// <param name="errorInfo">object containing information about the error</param>
  381. public virtual void OnErrorInfo(ErrorInfo errorInfo)
  382. {
  383. }
  384. }
  385. /// <summary>
  386. /// Container class for info about a particular message, RPC or update.
  387. /// </summary>
  388. /// \ingroup publicApi
  389. public struct PhotonMessageInfo
  390. {
  391. private readonly int timeInt;
  392. /// <summary>The sender of a message / event. May be null.</summary>
  393. public readonly Player Sender;
  394. public readonly PhotonView photonView;
  395. public PhotonMessageInfo(Player player, int timestamp, PhotonView view)
  396. {
  397. this.Sender = player;
  398. this.timeInt = timestamp;
  399. this.photonView = view;
  400. }
  401. [Obsolete("Use SentServerTime instead.")]
  402. public double timestamp
  403. {
  404. get
  405. {
  406. uint u = (uint) this.timeInt;
  407. double t = u;
  408. return t / 1000.0d;
  409. }
  410. }
  411. public double SentServerTime
  412. {
  413. get
  414. {
  415. uint u = (uint)this.timeInt;
  416. double t = u;
  417. return t / 1000.0d;
  418. }
  419. }
  420. public int SentServerTimestamp
  421. {
  422. get { return this.timeInt; }
  423. }
  424. public override string ToString()
  425. {
  426. return string.Format("[PhotonMessageInfo: Sender='{1}' Senttime={0}]", this.SentServerTime, this.Sender);
  427. }
  428. }
  429. /// <summary>Defines Photon event-codes as used by PUN.</summary>
  430. internal class PunEvent
  431. {
  432. public const byte RPC = 200;
  433. public const byte SendSerialize = 201;
  434. public const byte Instantiation = 202;
  435. public const byte CloseConnection = 203;
  436. public const byte Destroy = 204;
  437. public const byte RemoveCachedRPCs = 205;
  438. public const byte SendSerializeReliable = 206; // TS: added this but it's not really needed anymore
  439. public const byte DestroyPlayer = 207; // TS: added to make others remove all GOs of a player
  440. public const byte OwnershipRequest = 209;
  441. public const byte OwnershipTransfer = 210;
  442. public const byte VacantViewIds = 211;
  443. public const byte OwnershipUpdate = 212;
  444. }
  445. /// <summary>
  446. /// This container is used in OnPhotonSerializeView() to either provide incoming data of a PhotonView or for you to provide it.
  447. /// </summary>
  448. /// <remarks>
  449. /// The IsWriting property will be true if this client is the "owner" of the PhotonView (and thus the GameObject).
  450. /// Add data to the stream and it's sent via the server to the other players in a room.
  451. /// On the receiving side, IsWriting is false and the data should be read.
  452. ///
  453. /// Send as few data as possible to keep connection quality up. An empty PhotonStream will not be sent.
  454. ///
  455. /// Use either Serialize() for reading and writing or SendNext() and ReceiveNext(). The latter two are just explicit read and
  456. /// write methods but do about the same work as Serialize(). It's a matter of preference which methods you use.
  457. /// </remarks>
  458. /// \ingroup publicApi
  459. public class PhotonStream
  460. {
  461. private List<object> writeData;
  462. private object[] readData;
  463. private int currentItem; //Used to track the next item to receive.
  464. /// <summary>If true, this client should add data to the stream to send it.</summary>
  465. public bool IsWriting { get; private set; }
  466. /// <summary>If true, this client should read data send by another client.</summary>
  467. public bool IsReading
  468. {
  469. get { return !this.IsWriting; }
  470. }
  471. /// <summary>Count of items in the stream.</summary>
  472. public int Count
  473. {
  474. get { return this.IsWriting ? this.writeData.Count : this.readData.Length; }
  475. }
  476. /// <summary>
  477. /// Creates a stream and initializes it. Used by PUN internally.
  478. /// </summary>
  479. public PhotonStream(bool write, object[] incomingData)
  480. {
  481. this.IsWriting = write;
  482. if (!write && incomingData != null)
  483. {
  484. this.readData = incomingData;
  485. }
  486. }
  487. public void SetReadStream(object[] incomingData, int pos = 0)
  488. {
  489. this.readData = incomingData;
  490. this.currentItem = pos;
  491. this.IsWriting = false;
  492. }
  493. internal void SetWriteStream(List<object> newWriteData, int pos = 0)
  494. {
  495. if (pos != newWriteData.Count)
  496. {
  497. throw new Exception("SetWriteStream failed, because count does not match position value. pos: "+ pos + " newWriteData.Count:" + newWriteData.Count);
  498. }
  499. this.writeData = newWriteData;
  500. this.currentItem = pos;
  501. this.IsWriting = true;
  502. }
  503. internal List<object> GetWriteStream()
  504. {
  505. return this.writeData;
  506. }
  507. [Obsolete("Either SET the writeData with an empty List or use Clear().")]
  508. internal void ResetWriteStream()
  509. {
  510. this.writeData.Clear();
  511. }
  512. /// <summary>Read next piece of data from the stream when IsReading is true.</summary>
  513. public object ReceiveNext()
  514. {
  515. if (this.IsWriting)
  516. {
  517. Debug.LogError("Error: you cannot read this stream that you are writing!");
  518. return null;
  519. }
  520. object obj = this.readData[this.currentItem];
  521. this.currentItem++;
  522. return obj;
  523. }
  524. /// <summary>Read next piece of data from the stream without advancing the "current" item.</summary>
  525. public object PeekNext()
  526. {
  527. if (this.IsWriting)
  528. {
  529. Debug.LogError("Error: you cannot read this stream that you are writing!");
  530. return null;
  531. }
  532. object obj = this.readData[this.currentItem];
  533. //this.currentItem++;
  534. return obj;
  535. }
  536. /// <summary>Add another piece of data to send it when IsWriting is true.</summary>
  537. public void SendNext(object obj)
  538. {
  539. if (!this.IsWriting)
  540. {
  541. Debug.LogError("Error: you cannot write/send to this stream that you are reading!");
  542. return;
  543. }
  544. this.writeData.Add(obj);
  545. }
  546. [Obsolete("writeData is a list now. Use and re-use it directly.")]
  547. public bool CopyToListAndClear(List<object> target)
  548. {
  549. if (!this.IsWriting) return false;
  550. target.AddRange(this.writeData);
  551. this.writeData.Clear();
  552. return true;
  553. }
  554. /// <summary>Turns the stream into a new object[].</summary>
  555. public object[] ToArray()
  556. {
  557. return this.IsWriting ? this.writeData.ToArray() : this.readData;
  558. }
  559. /// <summary>
  560. /// Will read or write the value, depending on the stream's IsWriting value.
  561. /// </summary>
  562. public void Serialize(ref bool myBool)
  563. {
  564. if (this.IsWriting)
  565. {
  566. this.writeData.Add(myBool);
  567. }
  568. else
  569. {
  570. if (this.readData.Length > this.currentItem)
  571. {
  572. myBool = (bool) this.readData[this.currentItem];
  573. this.currentItem++;
  574. }
  575. }
  576. }
  577. /// <summary>
  578. /// Will read or write the value, depending on the stream's IsWriting value.
  579. /// </summary>
  580. public void Serialize(ref int myInt)
  581. {
  582. if (this.IsWriting)
  583. {
  584. this.writeData.Add(myInt);
  585. }
  586. else
  587. {
  588. if (this.readData.Length > this.currentItem)
  589. {
  590. myInt = (int) this.readData[this.currentItem];
  591. this.currentItem++;
  592. }
  593. }
  594. }
  595. /// <summary>
  596. /// Will read or write the value, depending on the stream's IsWriting value.
  597. /// </summary>
  598. public void Serialize(ref string value)
  599. {
  600. if (this.IsWriting)
  601. {
  602. this.writeData.Add(value);
  603. }
  604. else
  605. {
  606. if (this.readData.Length > this.currentItem)
  607. {
  608. value = (string) this.readData[this.currentItem];
  609. this.currentItem++;
  610. }
  611. }
  612. }
  613. /// <summary>
  614. /// Will read or write the value, depending on the stream's IsWriting value.
  615. /// </summary>
  616. public void Serialize(ref char value)
  617. {
  618. if (this.IsWriting)
  619. {
  620. this.writeData.Add(value);
  621. }
  622. else
  623. {
  624. if (this.readData.Length > this.currentItem)
  625. {
  626. value = (char) this.readData[this.currentItem];
  627. this.currentItem++;
  628. }
  629. }
  630. }
  631. /// <summary>
  632. /// Will read or write the value, depending on the stream's IsWriting value.
  633. /// </summary>
  634. public void Serialize(ref short value)
  635. {
  636. if (this.IsWriting)
  637. {
  638. this.writeData.Add(value);
  639. }
  640. else
  641. {
  642. if (this.readData.Length > this.currentItem)
  643. {
  644. value = (short) this.readData[this.currentItem];
  645. this.currentItem++;
  646. }
  647. }
  648. }
  649. /// <summary>
  650. /// Will read or write the value, depending on the stream's IsWriting value.
  651. /// </summary>
  652. public void Serialize(ref float obj)
  653. {
  654. if (this.IsWriting)
  655. {
  656. this.writeData.Add(obj);
  657. }
  658. else
  659. {
  660. if (this.readData.Length > this.currentItem)
  661. {
  662. obj = (float) this.readData[this.currentItem];
  663. this.currentItem++;
  664. }
  665. }
  666. }
  667. /// <summary>
  668. /// Will read or write the value, depending on the stream's IsWriting value.
  669. /// </summary>
  670. public void Serialize(ref Player obj)
  671. {
  672. if (this.IsWriting)
  673. {
  674. this.writeData.Add(obj);
  675. }
  676. else
  677. {
  678. if (this.readData.Length > this.currentItem)
  679. {
  680. obj = (Player) this.readData[this.currentItem];
  681. this.currentItem++;
  682. }
  683. }
  684. }
  685. /// <summary>
  686. /// Will read or write the value, depending on the stream's IsWriting value.
  687. /// </summary>
  688. public void Serialize(ref Vector3 obj)
  689. {
  690. if (this.IsWriting)
  691. {
  692. this.writeData.Add(obj);
  693. }
  694. else
  695. {
  696. if (this.readData.Length > this.currentItem)
  697. {
  698. obj = (Vector3) this.readData[this.currentItem];
  699. this.currentItem++;
  700. }
  701. }
  702. }
  703. /// <summary>
  704. /// Will read or write the value, depending on the stream's IsWriting value.
  705. /// </summary>
  706. public void Serialize(ref Vector2 obj)
  707. {
  708. if (this.IsWriting)
  709. {
  710. this.writeData.Add(obj);
  711. }
  712. else
  713. {
  714. if (this.readData.Length > this.currentItem)
  715. {
  716. obj = (Vector2) this.readData[this.currentItem];
  717. this.currentItem++;
  718. }
  719. }
  720. }
  721. /// <summary>
  722. /// Will read or write the value, depending on the stream's IsWriting value.
  723. /// </summary>
  724. public void Serialize(ref Quaternion obj)
  725. {
  726. if (this.IsWriting)
  727. {
  728. this.writeData.Add(obj);
  729. }
  730. else
  731. {
  732. if (this.readData.Length > this.currentItem)
  733. {
  734. obj = (Quaternion) this.readData[this.currentItem];
  735. this.currentItem++;
  736. }
  737. }
  738. }
  739. }
  740. public class SceneManagerHelper
  741. {
  742. public static string ActiveSceneName
  743. {
  744. get
  745. {
  746. Scene s = SceneManager.GetActiveScene();
  747. return s.name;
  748. }
  749. }
  750. public static int ActiveSceneBuildIndex
  751. {
  752. get { return SceneManager.GetActiveScene().buildIndex; }
  753. }
  754. #if UNITY_EDITOR
  755. /// <summary>In Editor, we can access the active scene's name.</summary>
  756. public static string EditorActiveSceneName
  757. {
  758. get { return SceneManager.GetActiveScene().name; }
  759. }
  760. #endif
  761. }
  762. /// <summary>
  763. /// The default implementation of a PrefabPool for PUN, which actually Instantiates and Destroys GameObjects but pools a resource.
  764. /// </summary>
  765. /// <remarks>
  766. /// This pool is not actually storing GameObjects for later reuse. Instead, it's destroying used GameObjects.
  767. /// However, prefabs will be loaded from a Resources folder and cached, which speeds up Instantiation a bit.
  768. ///
  769. /// The ResourceCache is public, so it can be filled without relying on the Resources folders.
  770. /// </remarks>
  771. public class DefaultPool : IPunPrefabPool
  772. {
  773. /// <summary>Contains a GameObject per prefabId, to speed up instantiation.</summary>
  774. public readonly Dictionary<string, GameObject> ResourceCache = new Dictionary<string, GameObject>();
  775. /// <summary>Returns an inactive instance of a networked GameObject, to be used by PUN.</summary>
  776. /// <param name="prefabId">String identifier for the networked object.</param>
  777. /// <param name="position">Location of the new object.</param>
  778. /// <param name="rotation">Rotation of the new object.</param>
  779. /// <returns></returns>
  780. public GameObject Instantiate(string prefabId, Vector3 position, Quaternion rotation)
  781. {
  782. GameObject res = null;
  783. bool cached = this.ResourceCache.TryGetValue(prefabId, out res);
  784. if (!cached)
  785. {
  786. res = Resources.Load<GameObject>(prefabId);
  787. if (res == null)
  788. {
  789. Debug.LogError("DefaultPool failed to load \"" + prefabId + "\". Make sure it's in a \"Resources\" folder. Or use a custom IPunPrefabPool.");
  790. }
  791. else
  792. {
  793. this.ResourceCache.Add(prefabId, res);
  794. }
  795. }
  796. bool wasActive = res.activeSelf;
  797. if (wasActive) res.SetActive(false);
  798. GameObject instance =GameObject.Instantiate(res, position, rotation) as GameObject;
  799. if (wasActive) res.SetActive(true);
  800. return instance;
  801. }
  802. /// <summary>Simply destroys a GameObject.</summary>
  803. /// <param name="gameObject">The GameObject to get rid of.</param>
  804. public void Destroy(GameObject gameObject)
  805. {
  806. GameObject.Destroy(gameObject);
  807. }
  808. }
  809. /// <summary>Small number of extension methods that make it easier for PUN to work cross-Unity-versions.</summary>
  810. public static class PunExtensions
  811. {
  812. public static Dictionary<MethodInfo, ParameterInfo[]> ParametersOfMethods = new Dictionary<MethodInfo, ParameterInfo[]>();
  813. public static ParameterInfo[] GetCachedParemeters(this MethodInfo mo)
  814. {
  815. ParameterInfo[] result;
  816. bool cached = ParametersOfMethods.TryGetValue(mo, out result);
  817. if (!cached)
  818. {
  819. result = mo.GetParameters();
  820. ParametersOfMethods[mo] = result;
  821. }
  822. return result;
  823. }
  824. public static PhotonView[] GetPhotonViewsInChildren(this UnityEngine.GameObject go)
  825. {
  826. return go.GetComponentsInChildren<PhotonView>(true) as PhotonView[];
  827. }
  828. public static PhotonView GetPhotonView(this UnityEngine.GameObject go)
  829. {
  830. return go.GetComponent<PhotonView>() as PhotonView;
  831. }
  832. /// <summary>compares the squared magnitude of target - second to given float value</summary>
  833. public static bool AlmostEquals(this Vector3 target, Vector3 second, float sqrMagnitudePrecision)
  834. {
  835. return (target - second).sqrMagnitude < sqrMagnitudePrecision; // TODO: inline vector methods to optimize?
  836. }
  837. /// <summary>compares the squared magnitude of target - second to given float value</summary>
  838. public static bool AlmostEquals(this Vector2 target, Vector2 second, float sqrMagnitudePrecision)
  839. {
  840. return (target - second).sqrMagnitude < sqrMagnitudePrecision; // TODO: inline vector methods to optimize?
  841. }
  842. /// <summary>compares the angle between target and second to given float value</summary>
  843. public static bool AlmostEquals(this Quaternion target, Quaternion second, float maxAngle)
  844. {
  845. return Quaternion.Angle(target, second) < maxAngle;
  846. }
  847. /// <summary>compares two floats and returns true of their difference is less than floatDiff</summary>
  848. public static bool AlmostEquals(this float target, float second, float floatDiff)
  849. {
  850. return Mathf.Abs(target - second) < floatDiff;
  851. }
  852. public static bool CheckIsAssignableFrom(this Type to, Type from)
  853. {
  854. #if !NETFX_CORE
  855. return to.IsAssignableFrom(from);
  856. #else
  857. return to.GetTypeInfo().IsAssignableFrom(from.GetTypeInfo());
  858. #endif
  859. }
  860. public static bool CheckIsInterface(this Type to)
  861. {
  862. #if !NETFX_CORE
  863. return to.IsInterface;
  864. #else
  865. return to.GetTypeInfo().IsInterface;
  866. #endif
  867. }
  868. }
  869. }