116 lines
3.4 KiB
C#
116 lines
3.4 KiB
C#
using UnityEngine;
|
|
using Unity.Netcode;
|
|
|
|
namespace Northbound
|
|
{
|
|
public class NetworkConnectionHelper : MonoBehaviour
|
|
{
|
|
[Header("Connection Settings")]
|
|
[SerializeField] private string serverIP = "127.0.0.1";
|
|
[SerializeField] private ushort port = 7777;
|
|
|
|
[Header("Auto Start")]
|
|
[SerializeField] private bool autoStartAsHost = false;
|
|
|
|
private void Start()
|
|
{
|
|
if (autoStartAsHost && ShouldAutoStart())
|
|
{
|
|
StartHost();
|
|
}
|
|
}
|
|
|
|
private bool ShouldAutoStart()
|
|
{
|
|
#if UNITY_EDITOR
|
|
return true;
|
|
#else
|
|
return !onlyInEditor;
|
|
#endif
|
|
}
|
|
|
|
public void StartHost()
|
|
{
|
|
if (NetworkManager.Singleton == null)
|
|
{
|
|
Debug.LogError("[NetworkConnectionHelper] NetworkManager not found!");
|
|
return;
|
|
}
|
|
|
|
ConfigureTransport("0.0.0.0", port);
|
|
|
|
if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsClient)
|
|
{
|
|
NetworkManager.Singleton.StartHost();
|
|
}
|
|
}
|
|
|
|
public void StartClient()
|
|
{
|
|
if (NetworkManager.Singleton == null)
|
|
{
|
|
Debug.LogError("[NetworkConnectionHelper] NetworkManager not found!");
|
|
return;
|
|
}
|
|
|
|
ConfigureTransport(serverIP, port);
|
|
|
|
if (!NetworkManager.Singleton.IsClient && !NetworkManager.Singleton.IsServer)
|
|
{
|
|
NetworkManager.Singleton.StartClient();
|
|
Debug.Log($"[NetworkConnectionHelper] Connecting to {serverIP}:{port}");
|
|
}
|
|
}
|
|
|
|
public void StartServer()
|
|
{
|
|
if (NetworkManager.Singleton == null)
|
|
{
|
|
Debug.LogError("[NetworkConnectionHelper] NetworkManager not found!");
|
|
return;
|
|
}
|
|
|
|
ConfigureTransport("0.0.0.0", port);
|
|
|
|
if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsClient)
|
|
{
|
|
NetworkManager.Singleton.StartServer();
|
|
Debug.Log($"[NetworkConnectionHelper] Started Server on port {port}");
|
|
}
|
|
}
|
|
|
|
public void Disconnect()
|
|
{
|
|
if (NetworkManager.Singleton != null)
|
|
{
|
|
NetworkManager.Singleton.Shutdown();
|
|
Debug.Log("[NetworkConnectionHelper] Disconnected");
|
|
}
|
|
}
|
|
|
|
public string GetStatus()
|
|
{
|
|
if (NetworkManager.Singleton == null)
|
|
return "NetworkManager not found";
|
|
|
|
if (NetworkManager.Singleton.IsHost)
|
|
return "Hosting";
|
|
if (NetworkManager.Singleton.IsServer)
|
|
return "Server";
|
|
if (NetworkManager.Singleton.IsClient)
|
|
return "Client";
|
|
|
|
return "Not connected";
|
|
}
|
|
|
|
private void ConfigureTransport(string ip, ushort portNum)
|
|
{
|
|
var transport = NetworkManager.Singleton.GetComponent<Unity.Netcode.Transports.UTP.UnityTransport>();
|
|
if (transport != null)
|
|
{
|
|
transport.SetConnectionData(ip, portNum);
|
|
}
|
|
}
|
|
}
|
|
}
|