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.

98 lines
2.5 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. [Header("Player Settings")]
  21. [SerializeField]
  22. [Tooltip("Player Name")]
  23. private string DisplayName;
  24. [SerializeField]
  25. [Tooltip("Player Color")]
  26. private Color PlayerColor;
  27. [Header("References")]
  28. [SerializeField]
  29. [Tooltip("Reference to actual Client")]
  30. protected ClientObject Client;
  31. #endregion Inspector Fields
  32. #region Private variables
  33. #endregion Private variables
  34. // Start is called before the first frame update
  35. private void Awake()
  36. {
  37. if (StartClientOnAwake)
  38. StartClient(ServerIP, Port);
  39. }
  40. public void OnEnable()
  41. {
  42. if (Client.isConnected)
  43. RegisterHandlers();
  44. }
  45. public void OnDisable()
  46. {
  47. Client.client.UnregisterHandler(LoginProtocols.RequestLoginDetails);
  48. }
  49. public void StartClient(string ipAddress, int port)
  50. {
  51. Client.Connect(ipAddress, port);
  52. RegisterHandlers();
  53. }
  54. public void RegisterHandlers()
  55. {
  56. Client.client.RegisterHandler(LoginProtocols.RequestLoginDetails, LoginRecieved);
  57. Client.client.RegisterHandler(LoginProtocols.LoginSuccess, LoginSucess);
  58. Client.client.RegisterHandler(LoginProtocols.LoginFail, LoginFail);
  59. }
  60. public void LoginRecieved(NetworkMessage msg)
  61. {
  62. Debug.Log("Connected to Server. Sending login details");
  63. Client.client.Send(LoginProtocols.SendingLoginDetails, new LoginProtocols.LoginMsg(DisplayName, PlayerColor));
  64. }
  65. public void LoginSucess(NetworkMessage msg)
  66. {
  67. Debug.Log("Log in successful");
  68. Client.UpdatePlayerDetails(DisplayName, PlayerColor);
  69. }
  70. public void LoginFail(NetworkMessage msg)
  71. {
  72. Debug.Log("Log in failed");
  73. Client.Stop();
  74. }
  75. }
  76. }