S&box Wiki

Revision Difference

using_lobbies#550954

<cat>UI.GameMenu</cat>⤶ <title>Using Lobbies</title>⤶ ⤶ # What are lobbies?⤶ ⤶ Imagine a lobby like a chat room. You can get a group of players in one and they can chat to each other. When lobbies have no players in them, they die.⤶ ⤶ # The Owner⤶ ⤶ Lobbies always have an owner. It's usually the first person to enter the lobby. When the owner leaves, ownership is handed down to someone else.⤶ ⤶ The owner can control aspects of the lobby, such as the lobby data.⤶ ⤶ # Networking⤶ ⤶ Members of lobbies have network connections, just like being attached to a server. You can send a network message to anyone in the lobby, and they can send a message to you.⤶ ⤶ This uses Steam's Game Network Sockets library, which breaks through your firewall and completely hides your IP address from other players. Messages are sent to your Steam Id - not your IP address.⤶ ⤶ Despite that, it's super fast and super reliable. This is the exact same network system that the main game uses.⤶ ⤶ # Joining a Lobby⤶ ⤶ ```⤶ // get lobbies⤶ var lobbies = await Game.Menu.QueryLobbiesAsync();⤶ ⤶ // get the most full⤶ var lobby = lobbies.OrderByDescending( x => x.MemberCount ).FirstOrDefault();⤶ ⤶ // join it⤶ await lobby.JoinAsync();⤶ ```⤶ ⤶ # Creating a Lobby⤶ ⤶ ```⤶ var lobby = await Game.Menu.CreateLobbyAsync( maxPlayers );⤶ lobby.Name = "My Stupid Lobby!";⤶ ```⤶ ⤶ # Leaving a Lobby⤶ ⤶ ```⤶ lobby.Leave();⤶ ```⤶ ⤶ # Getting players in a lobby⤶ ⤶ ```⤶ foreach( Friend f in lobby.Members )⤶ {⤶ Log.Info( $"{f.Name} is in the lobby!" );⤶ }⤶ ```⤶ ⤶ # Sending Chat⤶ ⤶ ```⤶ lobby.SendChat( "My Chat Message" );⤶ ```⤶ ⤶ # Receiving Chat⤶ ⤶ ```⤶ lobby.OnChatMessage = OnChatMessage;⤶ ⤶ ⤶ void OnChatMessage( Friend friend, string message )⤶ {⤶ Log.Warning( $"{friend.Name}: {message}" );⤶ }⤶ ⤶ ```⤶ ⤶ # Sending Network Message⤶ ⤶ ```⤶ // create a data message⤶ var data = ByteStream.Create( 256 );⤶ data.Write( 32 );⤶ data.Write( "Kill" );⤶ data.Write( new Vector3( 1, 2, 3 ) );⤶ ⤶ // send to everyone in the lobby⤶ Lobby.BroadcastMessage( data );⤶ ```⤶ ⤶ # Receiving Network Message⤶ ⤶ ```⤶ // read messages using this method⤶ Lobby.ReceiveMessages( OnNetworkMessage );⤶ ⤶ ⤶ void OnNetworkMessage( ILobby.NetworkMessage msg )⤶ {⤶ // source is the Friend that has sent the message⤶ Log.Info( $"Mesage from {msg.Source.Name}");⤶ ⤶ // raw byte data⤶ ByteStream data = msg.Data;⤶ ⤶ var messageId = data.Read<int>();⤶ ⤶ if ( messageId == 32 )⤶ {⤶ string action = data.Read<string>();⤶ Vector3 location = data.Read<Vector3>();⤶ ⤶ DoSomething( action, location );⤶ }⤶ }⤶ ```⤶ ⤶ ⤶ ⤶