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.
 
 
 
 

129 lines
3.3 KiB

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
namespace Networking.Client
{
public class ClientLoginManager : MonoBehaviour
{
#region Inspector Fields
[Header("Connection Settings")]
[SerializeField]
[Tooltip("Server Address to Connect to")]
private string ServerIP;
[SerializeField]
[Tooltip("Port to connect on")]
private int Port;
[SerializeField]
[Tooltip("Try and connect on Play")]
private bool StartClientOnAwake;
[Header("Player Settings")]
[SerializeField]
[Tooltip("Player Name")]
private string DisplayName;
[SerializeField]
[Tooltip("Player Color")]
private Color PlayerColor;
[Header("References")]
[SerializeField]
[Tooltip("Reference to actual Client")]
protected ClientObject Client;
[Header("Debug")]
[SerializeField]
[Tooltip("Send prefilled Player settings after connecting")]
private bool IdentifyOnConnect = false;
#endregion Inspector Fields
#region Events
public System.Action OnConnectedToServer;
public System.Action OnLoginSucess;
public System.Action OnLoginFail;
#endregion Events
#region Private variables
#endregion Private variables
// Start is called before the first frame update
private void Awake()
{
if (StartClientOnAwake)
StartClient(ServerIP, Port);
}
public void OnEnable()
{
if (Client.isConnected)
RegisterHandlers();
}
public void OnDisable()
{
Client.client.UnregisterHandler(LoginProtocols.RequestLoginDetails);
}
public void StartClient(string ipAddress, int port)
{
Client.Connect(ipAddress, port);
RegisterHandlers();
}
public void RegisterHandlers()
{
Client.client.RegisterHandler(LoginProtocols.RequestLoginDetails, ConnectedToServer);
Client.client.RegisterHandler(LoginProtocols.LoginSuccess, LoginSucess);
Client.client.RegisterHandler(LoginProtocols.LoginFail, LoginFail);
}
public void ConnectedToServer(NetworkMessage msg)
{
Debug.Log("Connected to Server.");
OnConnectedToServer.Invoke();
if (IdentifyOnConnect)
SendPlayerDetails(DisplayName,PlayerColor);
}
public void SendPlayerDetails(string name, Color color)
{
Debug.Log("Sending player Details.");
DisplayName = name;
PlayerColor = color;
Client.client.Send(LoginProtocols.SendingLoginDetails, new LoginProtocols.LoginMsg(DisplayName, PlayerColor));
}
public void LoginSucess(NetworkMessage msg)
{
Debug.Log("Log in successful!");
OnLoginSucess.Invoke();
Client.UpdatePlayerDetails(DisplayName, PlayerColor);
}
public void LoginFail(NetworkMessage msg)
{
Debug.Log("Log in failed!");
OnLoginFail.Invoke();
Client.Stop();
}
}
}