Session creation
Configure session options and choose network connection types to add multiplayer support to your project.
Read time 2 minutesLast updated 12 hours ago
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:
The CreateOrJoinSessionAsync method
Use theCreateOrJoinSessionAsync- Join an existing session with the given ID.
- Create a session if the ID doesn't exist.
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 toClass SessionOptionsExample: Creating a session with a client-hosted solution
The following example demonstrates how to create a session using a Unity client-hosted solution:In this code: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}");}
- The variable sets the maximum number of players allowed in the session, including the host. In this example, the maximum number of players is two.
MaxPlayers - The variable options of class can determine other session options, such as the session’s name, and whether it is password protected.
SessionOptions - The use of (or
WithRelayNetwork()) 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].WithDistributedAuthorityNetwork() - The line creates the session, and makes the player the host.
var session = await MultiplayerService.Instance.CreateSessionAsync(options); - The final line, , 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 in
Debug.Log($"Session {session.Id} created! Join code: {session.Code}");and use that variable instead.var joinCode = session.Code;