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; [SerializeField] private bool onlyInEditor = true; 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(); Debug.Log($"[NetworkConnectionHelper] Started Host on port {port}"); } } 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(); if (transport != null) { transport.SetConnectionData(ip, portNum); } } } }