Component that manages the network session lifecycle for the game. It exposes a CreateSession method that creates a lobby with a MaxPlayers limit and spawns a persistent LobbyFlow GameObject if one is not present. It also exposes IsHosting bound to Networking.IsHost.
using Sandbox.Network;
namespace Machines.Components;
/// <summary>
/// Owns the network session lifecycle; the game mode spawns cars from Connection.All directly.
/// </summary>
public sealed class NetworkSession : Component
{
/// <summary>
/// Max lobby connections (players + spectators).
/// </summary>
public const int MaxLobbyConnections = 16;
public bool IsHosting => Networking.IsHost;
/// <summary>
/// Create and host a new session.
/// </summary>
public void CreateSession()
{
Networking.CreateLobby( new LobbyConfig { MaxPlayers = MaxLobbyConnections } );
SpawnLobbyFlow();
}
private void SpawnLobbyFlow()
{
if ( LobbyFlow.Current != null )
return;
var go = new GameObject( "LobbyFlow" );
go.Flags |= GameObjectFlags.DontDestroyOnLoad;
go.AddComponent<LobbyFlow>();
go.NetworkSpawn();
}
}