using UnityEngine;
using Unity.Netcode;
using Unity.Netcode.Transports.UTP;
using System.Net.Sockets;
using System.Net;
namespace Northbound
{
///
/// Completely restarts network to fix stuck/closed port issues
///
public class NetworkResetAndRestart : MonoBehaviour
{
[Header("Reset Settings")]
[SerializeField] private bool autoResetOnStart = false;
[SerializeField] private ushort targetPort = 40445;
private NetworkManager _networkManager;
private UnityTransport _transport;
private void Start()
{
if (autoResetOnStart)
{
StartCoroutine(DoResetAndRestart());
}
}
[ContextMenu("Reset Network and Restart Host")]
public void ExecuteResetAndRestart()
{
StartCoroutine(DoResetAndRestart());
}
private System.Collections.IEnumerator DoResetAndRestart()
{
Debug.Log("=== NETWORK RESET AND RESTART ===");
// Step 1: Get references
_networkManager = NetworkManager.Singleton;
if (_networkManager == null)
{
Debug.LogError("[NetworkReset] NetworkManager not found!");
yield break;
}
_transport = _networkManager.GetComponent();
if (_transport == null)
{
Debug.LogError("[NetworkReset] UnityTransport not found!");
yield break;
}
// Step 2: Log current state
LogCurrentState();
// Step 3: Shutdown if running
if (_networkManager.IsServer || _networkManager.IsClient)
{
Debug.Log("[NetworkReset] Shutting down current network...");
_networkManager.Shutdown();
// Wait for complete shutdown
float startTime = Time.time;
while ((_networkManager.IsServer || _networkManager.IsClient) && Time.time - startTime < 10f)
{
yield return new WaitForSeconds(0.1f);
}
Debug.Log("[NetworkReset] ✓ Network shutdown complete");
}
yield return new WaitForSeconds(1f);
// Step 4: Force port release
ForcePortRelease();
yield return new WaitForSeconds(1f);
// Step 5: Reconfigure transport
Debug.Log("[NetworkReset] Reconfiguring transport...");
_transport.SetConnectionData(
"0.0.0.0", // Listen on all interfaces
targetPort, // Port 40445
"0.0.0.0" // Server listen on all interfaces
);
Debug.Log("[NetworkReset] ✓ Transport configured to 0.0.0.0:" + targetPort + "");
Debug.Log("[NetworkReset] ✓ Server will accept connections from ANY IP");
yield return new WaitForSeconds(0.5f);
// Step 6: Start host
Debug.Log("[NetworkReset] Starting fresh host...");
_networkManager.StartHost();
// Wait for host to start
float hostStartTime = Time.time;
while (!_networkManager.IsServer && Time.time - hostStartTime < 10f)
{
yield return new WaitForSeconds(0.2f);
}
if (_networkManager.IsServer)
{
Debug.Log("[NetworkReset] ✓ Host started successfully!");
// Verify port is actually listening
yield return new WaitForSeconds(1f);
VerifyPortListening();
}
else
{
Debug.LogError("[NetworkReset] ✗ Failed to start host!");
}
Debug.Log("=== RESET AND RESTART COMPLETE ===");
}
private void LogCurrentState()
{
Debug.Log("[NetworkReset] Current Network State:");
Debug.Log(" IsServer: " + _networkManager.IsServer);
Debug.Log(" IsClient: " + _networkManager.IsClient);
Debug.Log(" IsHost: " + _networkManager.IsHost);
Debug.Log(" IsConnectedClient: " + _networkManager.IsConnectedClient);
Debug.Log(" LocalClientId: " + _networkManager.LocalClientId);
Debug.Log(" ConnectedClients: " + _networkManager.ConnectedClients.Count);
if (_transport != null)
{
Debug.Log(" Transport.Port: " + _transport.ConnectionData.Port);
Debug.Log(" Transport.Address: " + _transport.ConnectionData.Address);
}
}
private void ForcePortRelease()
{
Debug.Log("[NetworkReset] Forcing port release...");
try
{
// Try to bind and release port to ensure it's freed
TcpListener testListener = new TcpListener(IPAddress.Any, targetPort);
testListener.Start();
testListener.Stop();
Debug.Log("[NetworkReset] ✓ Port " + targetPort + " is released");
}
catch (System.Exception e)
{
Debug.LogWarning("[NetworkReset] ⚠ Could not bind port for release: " + e.Message + "");
Debug.LogWarning("[NetworkReset] This is normal if port is in use");
}
}
private void VerifyPortListening()
{
Debug.Log("[NetworkReset] Verifying port is listening...");
try
{
using (TcpClient client = new TcpClient("127.0.0.1", targetPort))
{
Debug.Log("[NetworkReset] ✓ Successfully connected to localhost:" + targetPort + "");
Debug.Log("[NetworkReset] ✓ Unity IS listening on port");
Debug.Log("[NetworkReset] ✓ Port should now be accessible on yougetsignal");
Debug.Log("");
Debug.Log("[NetworkReset] ✓ TEST ON YOUGETSIGNAL NOW!");
}
}
catch (System.Exception e)
{
Debug.LogWarning("[NetworkReset] ⚠ Could not connect to localhost:" + targetPort + "");
Debug.LogWarning("[NetworkReset] Error: " + e.Message);
Debug.LogWarning("[NetworkReset] This might mean server didn't actually start");
}
}
[ContextMenu("Check Current Network Status")]
public void CheckStatus()
{
_networkManager = NetworkManager.Singleton;
if (_networkManager == null)
{
Debug.LogError("NetworkManager not found");
return;
}
Debug.Log("=== NETWORK STATUS ===");
Debug.Log("IsServer: " + _networkManager.IsServer);
Debug.Log("IsClient: " + _networkManager.IsClient);
Debug.Log("IsHost: " + _networkManager.IsHost);
Debug.Log("IsConnectedClient: " + _networkManager.IsConnectedClient);
Debug.Log("LocalClientId: " + _networkManager.LocalClientId);
Debug.Log("ConnectedClients: " + _networkManager.ConnectedClients.Count);
foreach (var client in _networkManager.ConnectedClients)
{
Debug.Log(" Client " + client.Key + ": " +
(client.Value.PlayerObject != null ? "Has Player" : "No Player"));
}
Debug.Log("===================");
}
[ContextMenu("Generate Instructions")]
public void GenerateInstructions()
{
Debug.Log("=== NETWORK RESET INSTRUCTIONS ===");
Debug.Log("");
Debug.Log("PROBLEM:");
Debug.Log("- Port stays closed even though config is correct");
Debug.Log("- Server reports running but port not accessible");
Debug.Log("");
Debug.Log("SOLUTION: Complete network reset");
Debug.Log("");
Debug.Log("STEPS:");
Debug.Log("1. Add NetworkResetAndRestart to scene");
Debug.Log("2. Right-click → 'Reset Network and Restart Host'");
Debug.Log("3. Wait for '✓ Host started successfully'");
Debug.Log("4. Test on yougetsignal IMMEDIATELY");
Debug.Log("");
Debug.Log("WHAT IT DOES:");
Debug.Log("1. Shuts down any current network");
Debug.Log("2. Forces port release");
Debug.Log("3. Reconfigures transport to 0.0.0.0");
Debug.Log("4. Starts fresh host");
Debug.Log("5. Verifies port is actually listening");
Debug.Log("");
Debug.Log("EXPECTED RESULT:");
Debug.Log("✓ Port 40445 shows OPEN on yougetsignal");
Debug.Log("✓ Teammates can connect");
Debug.Log("===============================");
}
}
}