Session creation
Configure session options and choose network connection types to add multiplayer support to your project.
Note: The Multiplayer Services SDK uses sessions to manage groups of players. Sessions relies internally on different combinations of Unity Gaming Services such as Relay, Distributed Authority, Lobby, Matchmaker and Multiplay Hosting, and thus contributes to the billing of those services.
To start a multiplayer game, the host must create a session that other players join to participate in the game. This page outlines what you must include in your script to create a session. Consider the following factors when you create a session:
Note: To access the API for the Multiplayer Services SDK, import the SDK's namespace in your script:
using Unity.Services.Multiplayer;
The CreateOrJoinSessionAsync method
Use the CreateOrJoinSessionAsync
method to do the following:
- Join an existing session with the given ID.
- Create a session if the ID doesn't exist.
This approach ensures that only one session is created when multiple clients attempt to join the same session, often referred to as race conditions.
var session = await MultiplayerService.Instance.CreateOrJoinSessionAsync(sessionId, options)
Session options properties
The session options determine various properties of your session, such as the maximum number of players, or whether the session is password protected.
Refer to Class SessionOptions
for a full list of options.
Network connection
Players can create and join sessions using different network connection types and configuration options.
Types of network
The following network connections types are available:
- Direct network connection.
- Client-hosted solutions by Unity, using Relay or Distributed Authority. This practice is recommended for peer-to-peer games played over the internet.
Refer to Class SessionOptions > Methods
for more information.
Configurable network options
You can override the default network options of your sessions, including both direct and relay-based networking.
If you do not specify network options when calling the WithRelayNetwork()
,WithDirectNetwork()
or WithDistributedAuthorityNetwork()
methods, the Session system automatically applies its default settings to configure the requested network type. For details about default values and behaviors for these methods, refer to Class SessionOptionsExtensions.
DirectNetworkOptions
Configure direct network connections with DirectNetworkOptions
. Use these options with WithDirectNetwork()
when setting a SessionOption
to override the default behavior.
The following settings are available:
- ListenIp: The IPv4 or IPv6 address to listen for incoming connections.
- PublishIp: The IPv4 or IPv6 address to publish for other clients to connect to.
- Port: The port number used for both listening and publishing endpoints.
Using direct networking in client-hosted games reveals the IP address of players to the host. For client-hosted games, the recommended best practice to to use Relay or Distributed Authority to handle NAT, firewalls, and protect player privacy.
Not all platforms support IPv6 connections. Only use IPv6 addresses once you verified that your target platform(s) supports it.
RelayNetworkOptions
Configure relay protocol-based network connections with RelayNetworkOptions
. Use with the WithRelayNetwork()
or WithDistributedAuthorityNetwork()
when setting SessionOption
to override the default behavior.
The following settings are available:
- Protocol: The network protocol that the Relay connection uses.
- Region: Forces a specific Relay region to be used, and skips auto-selection from QoS results.
- PreserveRegion: If enabled, saves the relay region to session properties, and reuses it in case of host migration.
The following Relay protocols are supported:
- User Datagram Protocol (UDP)
- Datagram Transport Layer Security (DTLS)
- Secure websocket (WSS)
The recommended Default
protocol may vary between platforms.
Example: Creating a session with a client-hosted solution
The following example demonstrates how to create a session using a Unity client-hosted solution:
async Task StartSessionAsHost()
{
var options = new SessionOptions
{
MaxPlayers = 2
}.WithRelayNetwork(); // or WithDistributedAuthorityNetwork() to use Distributed Authority instead of Relay
var session = await MultiplayerService.Instance.CreateSessionAsync(options);
Debug.Log($"Session {session.Id} created! Join code: {session.Code}");
}
In this code:
- The variable
MaxPlayers
sets the maximum number of players allowed in the session, including the host. In this example, the maximum number of players is two. - The variable options of class
SessionOptions
can determine other session options, such as the session’s name, and whether it is password protected. - The use of
WithRelayNetwork()
(orWithDistributedAuthorityNetwork()
) configures the session to use Relay (or Distributed Authority) networking rather than direct connections (in other words, with a fixed IP address and port). This is the recommended best practice for peer-to-peer connectivity over the Internet. Refer to Relay or [Distributed Authority]. - The line
var session = await MultiplayerService.Instance.CreateSessionAsync(options);
creates the session, and makes the player the host. - The final line,
Debug.Log($"Session {session.Id} created! Join code: {session.Code}");
, displays the session ID and join code in the console of the Unity Editor. The host would then share this join code with the other players. Alternatively, you could create a variable to get the join code, as invar joinCode = session.Code;
and use that variable instead.
Example: Creating a session with a client-hosted solution with overridden default relay options
The following example demonstrates how to create a session using a Unity client-hosted solution with overridden options provided to the relay allocation:
// When the region is specified, it forces the use of a specific Relay region, and skips QoS auto-selection.
async Task StartSessionAsHost(string region = null)
{
var options = new SessionOptions
{
MaxPlayers = 2
}.WithRelayNetwork(new RelayNetworkOptions(RelayProtocol.Default, region, true)); // or WithDistributedAuthorityNetwork() to use Distributed Authority instead of Relay
var session = await MultiplayerService.Instance.CreateSessionAsync(options);
Debug.Log($"Session {session.Id} created! Join code: {session.Code}");
}
The points from Example: Creating a session with a client-hosted solution also apply to this example, along with the following information:
- The
RelayNetworkOptions
class configures the session to start the relay connection using the platform-suggestedDefault
protocol using the providedregion
parameter. IfPreserveRegion
is set to true, the newly-elected host won't change the relay allocation region in the event of a host migration. If set to false, the region might change. - If the region is not passed as a parameter, the default
null
value triggers a QoS query to determine the most optimal region for the relay allocation. For the list of available regions, refer to Relay locations and regions.
Using a custom network handler
Advanced users can specify a custom network handler by implementing INetworkHandler, which overrides the default integration with Netcode for Game Objects and Netcode for Entities.
var options = new SessionOptions { MaxPlayers = 2 }
.WithRelayNetwork()
.WithNetworkHandler(new CustomEntitiesNetworkHandler());