Launcher.cs 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. // --------------------------------------------------------------------------------------------------------------------
  2. // <copyright file="Launcher.cs" company="Exit Games GmbH">
  3. // Part of: Photon Unity Networking Demos
  4. // </copyright>
  5. // <summary>
  6. // Used in "PUN Basic tutorial" to connect, and join/create room automatically
  7. // </summary>
  8. // <author>developer@exitgames.com</author>
  9. // --------------------------------------------------------------------------------------------------------------------
  10. using UnityEngine;
  11. using UnityEngine.UI;
  12. using Photon.Realtime;
  13. namespace Photon.Pun.Demo.PunBasics
  14. {
  15. #pragma warning disable 649
  16. /// <summary>
  17. /// Launch manager. Connect, join a random room or create one if none or all full.
  18. /// </summary>
  19. public class Launcher : MonoBehaviourPunCallbacks
  20. {
  21. #region Private Serializable Fields
  22. [Tooltip("The Ui Panel to let the user enter name, connect and play")]
  23. [SerializeField]
  24. private GameObject controlPanel;
  25. [Tooltip("The Ui Text to inform the user about the connection progress")]
  26. [SerializeField]
  27. private Text feedbackText;
  28. [Tooltip("The maximum number of players per room")]
  29. [SerializeField]
  30. private byte maxPlayersPerRoom = 4;
  31. [Tooltip("The UI Loader Anime")]
  32. [SerializeField]
  33. private LoaderAnime loaderAnime;
  34. #endregion
  35. #region Private Fields
  36. /// <summary>
  37. /// Keep track of the current process. Since connection is asynchronous and is based on several callbacks from Photon,
  38. /// we need to keep track of this to properly adjust the behavior when we receive call back by Photon.
  39. /// Typically this is used for the OnConnectedToMaster() callback.
  40. /// </summary>
  41. bool isConnecting;
  42. /// <summary>
  43. /// This client's version number. Users are separated from each other by gameVersion (which allows you to make breaking changes).
  44. /// </summary>
  45. string gameVersion = "1";
  46. #endregion
  47. #region MonoBehaviour CallBacks
  48. /// <summary>
  49. /// MonoBehaviour method called on GameObject by Unity during early initialization phase.
  50. /// </summary>
  51. void Awake()
  52. {
  53. if (loaderAnime==null)
  54. {
  55. Debug.LogError("<Color=Red><b>Missing</b></Color> loaderAnime Reference.",this);
  56. }
  57. // #Critical
  58. // this makes sure we can use PhotonNetwork.LoadLevel() on the master client and all clients in the same room sync their level automatically
  59. PhotonNetwork.AutomaticallySyncScene = true;
  60. }
  61. #endregion
  62. #region Public Methods
  63. /// <summary>
  64. /// Start the connection process.
  65. /// - If already connected, we attempt joining a random room
  66. /// - if not yet connected, Connect this application instance to Photon Cloud Network
  67. /// </summary>
  68. public void Connect()
  69. {
  70. // we want to make sure the log is clear everytime we connect, we might have several failed attempted if connection failed.
  71. feedbackText.text = "";
  72. // keep track of the will to join a room, because when we come back from the game we will get a callback that we are connected, so we need to know what to do then
  73. isConnecting = true;
  74. // hide the Play button for visual consistency
  75. controlPanel.SetActive(false);
  76. // start the loader animation for visual effect.
  77. if (loaderAnime!=null)
  78. {
  79. loaderAnime.StartLoaderAnimation();
  80. }
  81. // we check if we are connected or not, we join if we are , else we initiate the connection to the server.
  82. if (PhotonNetwork.IsConnected)
  83. {
  84. LogFeedback("Joining Room...");
  85. // #Critical we need at this point to attempt joining a Random Room. If it fails, we'll get notified in OnJoinRandomFailed() and we'll create one.
  86. PhotonNetwork.JoinRandomRoom();
  87. }else{
  88. LogFeedback("Connecting...");
  89. // #Critical, we must first and foremost connect to Photon Online Server.
  90. PhotonNetwork.ConnectUsingSettings();
  91. PhotonNetwork.GameVersion = this.gameVersion;
  92. }
  93. }
  94. /// <summary>
  95. /// Logs the feedback in the UI view for the player, as opposed to inside the Unity Editor for the developer.
  96. /// </summary>
  97. /// <param name="message">Message.</param>
  98. void LogFeedback(string message)
  99. {
  100. // we do not assume there is a feedbackText defined.
  101. if (feedbackText == null) {
  102. return;
  103. }
  104. // add new messages as a new line and at the bottom of the log.
  105. feedbackText.text += System.Environment.NewLine+message;
  106. }
  107. #endregion
  108. #region MonoBehaviourPunCallbacks CallBacks
  109. // below, we implement some callbacks of PUN
  110. // you can find PUN's callbacks in the class MonoBehaviourPunCallbacks
  111. /// <summary>
  112. /// Called after the connection to the master is established and authenticated
  113. /// </summary>
  114. public override void OnConnectedToMaster()
  115. {
  116. // we don't want to do anything if we are not attempting to join a room.
  117. // this case where isConnecting is false is typically when you lost or quit the game, when this level is loaded, OnConnectedToMaster will be called, in that case
  118. // we don't want to do anything.
  119. if (isConnecting)
  120. {
  121. LogFeedback("OnConnectedToMaster: Next -> try to Join Random Room");
  122. Debug.Log("PUN Basics Tutorial/Launcher: OnConnectedToMaster() was called by PUN. Now this client is connected and could join a room.\n Calling: PhotonNetwork.JoinRandomRoom(); Operation will fail if no room found");
  123. // #Critical: The first we try to do is to join a potential existing room. If there is, good, else, we'll be called back with OnJoinRandomFailed()
  124. PhotonNetwork.JoinRandomRoom();
  125. }
  126. }
  127. /// <summary>
  128. /// Called when a JoinRandom() call failed. The parameter provides ErrorCode and message.
  129. /// </summary>
  130. /// <remarks>
  131. /// Most likely all rooms are full or no rooms are available. <br/>
  132. /// </remarks>
  133. public override void OnJoinRandomFailed(short returnCode, string message)
  134. {
  135. LogFeedback("<Color=Red>OnJoinRandomFailed</Color>: Next -> Create a new Room");
  136. Debug.Log("PUN Basics Tutorial/Launcher:OnJoinRandomFailed() was called by PUN. No random room available, so we create one.\nCalling: PhotonNetwork.CreateRoom");
  137. // #Critical: we failed to join a random room, maybe none exists or they are all full. No worries, we create a new room.
  138. PhotonNetwork.CreateRoom(null, new RoomOptions { MaxPlayers = this.maxPlayersPerRoom});
  139. }
  140. /// <summary>
  141. /// Called after disconnecting from the Photon server.
  142. /// </summary>
  143. public override void OnDisconnected(DisconnectCause cause)
  144. {
  145. LogFeedback("<Color=Red>OnDisconnected</Color> "+cause);
  146. Debug.LogError("PUN Basics Tutorial/Launcher:Disconnected");
  147. // #Critical: we failed to connect or got disconnected. There is not much we can do. Typically, a UI system should be in place to let the user attemp to connect again.
  148. loaderAnime.StopLoaderAnimation();
  149. isConnecting = false;
  150. controlPanel.SetActive(true);
  151. }
  152. /// <summary>
  153. /// Called when entering a room (by creating or joining it). Called on all clients (including the Master Client).
  154. /// </summary>
  155. /// <remarks>
  156. /// This method is commonly used to instantiate player characters.
  157. /// If a match has to be started "actively", you can call an [PunRPC](@ref PhotonView.RPC) triggered by a user's button-press or a timer.
  158. ///
  159. /// When this is called, you can usually already access the existing players in the room via PhotonNetwork.PlayerList.
  160. /// Also, all custom properties should be already available as Room.customProperties. Check Room..PlayerCount to find out if
  161. /// enough players are in the room to start playing.
  162. /// </remarks>
  163. public override void OnJoinedRoom()
  164. {
  165. LogFeedback("<Color=Green>OnJoinedRoom</Color> with "+PhotonNetwork.CurrentRoom.PlayerCount+" Player(s)");
  166. Debug.Log("PUN Basics Tutorial/Launcher: OnJoinedRoom() called by PUN. Now this client is in a room.\nFrom here on, your game would be running.");
  167. // #Critical: We only load if we are the first player, else we rely on PhotonNetwork.AutomaticallySyncScene to sync our instance scene.
  168. if (PhotonNetwork.CurrentRoom.PlayerCount == 1)
  169. {
  170. Debug.Log("We load the 'Room for 1' ");
  171. // #Critical
  172. // Load the Room Level.
  173. PhotonNetwork.LoadLevel("PunBasics-Room for 1");
  174. }
  175. }
  176. #endregion
  177. }
  178. }