Course contentsShow
← Unity Game Development
Lesson 811 of 82812. Multiplayer and DeploymentFree lesson

Managing Player Presence and Session Discovery

Build a discovery system that allows players to query active lobbies and join friends using session codes or public lists.

In this lesson, you will learn how to build a discovery system that enables players to find active game sessions through public lists or direct codes using Unity’s Lobby service.

The Mechanism of Discovery

When players want to play together, they need a way to find each other before a network connection is established. This is the role of Session Discovery. Unlike the Relay service, which facilitates the actual data traffic, the Lobby service acts as a "phonebook" for your game.

To manage presence, you must ensure that your lobby maintains metadata—a collection of properties (like map name or game mode) that help players filter and find the session that fits their needs.

Implementing a Query System

To allow players to see active lobbies, you implement a query system. This involves defining QueryFilters that restrict the list returned to the client. Without filtering, your players might be overwhelmed by hundreds of global sessions.

// Example: Creating a query to find lobbies with specific criteria
QueryLobbiesOptions options = new QueryLobbiesOptions();
options.Filters = new List<QueryFilter> {
    new QueryFilter(QueryFilter.FieldOptions.AvailableSlots, "0", QueryFilter.OpOptions.GT),
    new QueryFilter(QueryFilter.FieldOptions.SMinPlayerCount, "2", QueryFilter.OpOptions.GE)
};

QueryResponse lobbies = await Lobbies.Instance.QueryLobbiesAsync(options);

Joining via Session Codes

While public lists are great for browsing, direct discovery is often faster for friends. By exposing the LobbyCode (a unique string generated when the host creates the lobby), you allow players to skip the list altogether. The joining player simply inputs this string, which your system passes into LobbyService.Instance.JoinLobbyByCodeAsync(lobbyCode).

Once the lobby is joined, your client receives the Allocation data from the Relay service attached to that lobby, allowing the NetworkManager to complete the connection handshake. This two-step process—discovering the session via the Lobby service and then connecting via Relay—is the industry standard for lobby-based multiplayer in Unity.

Key Takeaway: Session discovery decouples the act of finding a game from the act of connecting to it, using metadata filters for public browsing and unique codes for direct friend invites.