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.
 
 
 

88 lines
2.7 KiB

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
namespace Multiplayer
{
public class ClientManager : MonoBehaviour
{
#region Inspector Variables
[Header("Client Settings")]
[Tooltip("Address server is hosted on")]
[SerializeField]
private string ServerAddress = "127.0.0.1";
[Tooltip("Port to connect to server on")]
[SerializeField]
private int Port = 4444;
[Tooltip("Connects client to server on awake")]
[SerializeField]
private bool ConnectOnStart = false;
#endregion
//Returns if client is current connected to a server
public bool IsConnected { get; private set; }
//UNET client class which connects to the server;
private NetworkClient uNetClient;
/// <summary>
/// Call to connect client to host
/// </summary>
[ContextMenu("Start Client")]
public void StartClient()
{
StartClient(ServerAddress, Port);
}
/// <summary>
/// Call to connect the client to the host
/// </summary>
/// <param name="ServerAddress">Server Address to connect to</param>
/// <param name="Port">Port to connect on</param>
public void StartClient(string ServerAddress, int Port)
{
//If client is already connected to don't continue
if (IsConnected)
{
Debug.Log("Client already connected to a server. Client needs to disconnect before it can connect to a server");
return;
}
Debug.Log("Attempting to connect to: '" + ServerAddress + "' on port : '" + Port + "'");
uNetClient = new NetworkClient();
RegisterHandlers(uNetClient);
uNetClient.Configure(ChannelConfig.DefaultTopology());
uNetClient.Connect(ServerAddress, Port);
}
/// <summary>
/// Helper function which sets up all necessary handlers for message types
/// </summary>
/// <param name="client"></param>
private void RegisterHandlers(NetworkClient client)
{
client.RegisterHandler(MsgType.Connect, OnConnected);
client.RegisterHandler(MsgType.Disconnect, OnDisconnected);
}
private void OnConnected(NetworkMessage msg)
{
IsConnected = true;
Debug.Log("Successfully connected to server");
Debug.Log("Connection ID: " + msg.conn.connectionId);
}
private void OnDisconnected(NetworkMessage msg)
{
IsConnected = false;
Debug.Log("Disconnected from Server");
}
}
}