Files
megakoop/Networking/NGO/NetworkBootstrap.cs
2025-10-05 18:18:12 +02:00

78 lines
2.6 KiB
C#

using UnityEngine;
namespace MegaKoop.Networking
{
/// <summary>
/// Thin bootstrap around Netcode for GameObjects start/stop.
/// Uses compile guards so the project compiles without NGO.
/// </summary>
public static class NetworkBootstrap
{
public static bool StartHost(string gameScene = "GameScene")
{
#if UNITY_NETCODE || NETCODE_PRESENT
var nm = Unity.Netcode.NetworkManager.Singleton;
if (nm == null)
{
Debug.LogError("[NetworkBootstrap] NetworkManager.Singleton not found in scene.");
return false;
}
Object.DontDestroyOnLoad(nm.gameObject);
bool ok = nm.StartHost();
if (!ok)
{
Debug.LogError("[NetworkBootstrap] StartHost failed.");
return false;
}
// Prefer NGO SceneManager if available
if (nm.SceneManager != null)
{
nm.SceneManager.LoadScene(gameScene, Unity.Netcode.AdditiveScenes.NetworkSceneManager.LoadSceneMode.Single);
}
else
{
UnityEngine.SceneManagement.SceneManager.LoadScene(gameScene);
}
return true;
#else
Debug.LogWarning("[NetworkBootstrap] Netcode for GameObjects not present. Define UNITY_NETCODE or NETCODE_PRESENT and add the package.");
return false;
#endif
}
public static bool StartClient(string gameScene = "GameScene")
{
#if UNITY_NETCODE || NETCODE_PRESENT
var nm = Unity.Netcode.NetworkManager.Singleton;
if (nm == null)
{
Debug.LogError("[NetworkBootstrap] NetworkManager.Singleton not found in scene.");
return false;
}
Object.DontDestroyOnLoad(nm.gameObject);
bool ok = nm.StartClient();
if (!ok)
{
Debug.LogError("[NetworkBootstrap] StartClient failed.");
return false;
}
// Client will be moved to scene by NGO server scene management
return true;
#else
Debug.LogWarning("[NetworkBootstrap] Netcode for GameObjects not present. Define UNITY_NETCODE or NETCODE_PRESENT and add the package.");
return false;
#endif
}
public static void Stop()
{
#if UNITY_NETCODE || NETCODE_PRESENT
var nm = Unity.Netcode.NetworkManager.Singleton;
if (nm == null) return;
if (nm.IsServer || nm.IsHost) nm.Shutdown(true);
else if (nm.IsClient) nm.Shutdown();
#endif
}
}
}