You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

103 lines
2.7 KiB

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.Networking;
  5. namespace Networking.Client
  6. {
  7. public class ClientLoginManager : MonoBehaviour
  8. {
  9. #region Inspector Fields
  10. [Header("Connection Settings")]
  11. [SerializeField]
  12. [Tooltip("Server Address to Connect to")]
  13. private string ServerIP;
  14. [SerializeField]
  15. [Tooltip("Port to connect on")]
  16. private int Port;
  17. [SerializeField]
  18. [Tooltip("Try and connect on Play")]
  19. private bool StartClientOnAwake;
  20. [SerializeField]
  21. [Tooltip("Scene to load on connection")]
  22. private string LevelToLoad;
  23. [Header("Player Settings")]
  24. [SerializeField]
  25. [Tooltip("Player Name")]
  26. private string DisplayName;
  27. [SerializeField]
  28. [Tooltip("Player Color")]
  29. private Color PlayerColor;
  30. [Header("References")]
  31. [SerializeField]
  32. [Tooltip("Reference to actual Client")]
  33. protected ClientObject Client;
  34. #endregion Inspector Fields
  35. #region Private variables
  36. #endregion Private variables
  37. // Start is called before the first frame update
  38. private void Awake()
  39. {
  40. if (StartClientOnAwake)
  41. StartClient(ServerIP, Port);
  42. }
  43. public void OnEnable()
  44. {
  45. if (Client.isConnected)
  46. RegisterHandlers();
  47. }
  48. public void OnDisable()
  49. {
  50. Client.client.UnregisterHandler(LoginProtocols.RequestLoginDetails);
  51. }
  52. public void StartClient(string ipAddress, int port)
  53. {
  54. Client.Connect(ipAddress, port);
  55. RegisterHandlers();
  56. }
  57. public void RegisterHandlers()
  58. {
  59. Client.client.RegisterHandler(LoginProtocols.RequestLoginDetails, LoginRecieved);
  60. Client.client.RegisterHandler(LoginProtocols.LoginSuccess, LoginSucess);
  61. Client.client.RegisterHandler(LoginProtocols.LoginFail, LoginFail);
  62. }
  63. public void LoginRecieved(NetworkMessage msg)
  64. {
  65. Debug.Log("Connected to Server. Sending login details");
  66. Client.client.Send(LoginProtocols.SendingLoginDetails, new LoginProtocols.LoginMsg(DisplayName, PlayerColor));
  67. }
  68. public void LoginSucess(NetworkMessage msg)
  69. {
  70. Debug.Log("Log in successful");
  71. Client.UpdatePlayerDetails(DisplayName, PlayerColor);
  72. UnityEngine.SceneManagement.SceneManager.LoadScene(LevelToLoad);
  73. }
  74. public void LoginFail(NetworkMessage msg)
  75. {
  76. Debug.Log("Log in failed");
  77. Client.Stop();
  78. }
  79. }
  80. }