メインコンテンツまでスキップ

Create match session with the SDK - Create joinable sessions with peer-to-peer - (Unity module)

Last updated on November 25, 2024
備考

Browsing P2P sessions is not supported in WebGL builds due to the AccelByte Gaming Services (AGS) SDK for Unity lacking the P2P functionality for WebGL.

Unwrap the wrapper

In this tutorial, you will learn how to create a match session using the AGS Game SDK for Unity. In the Byte Wars project, there is already an SDK wrapper created called MatchSessionWrapper.cs. This class will call the AGS Game SDK for Unity API to create a match session.

There is also the P2PHelper.cs class provided that contains several functions for starting as a peer-to-peer (P2P) host and joining a P2P session. You can find the CS file in Assets/Resources/Modules/MatchmakingSessionP2P/Scripts/P2PHelper.cs.

There are two variables in P2PHelper.cs: transportManager, is a custom network transport from the AGS network transport, and networkManager to hold a reference to the NetworkManager class.

private static AccelByteNetworkTransportManager transportManager;
private static NetworkManager networkManager;

The Init function initializes the custom network transport.

private static void Init()
{
if (transportManager != null)
{
return;
}
networkManager = NetworkManager.Singleton;
transportManager = networkManager.gameObject.AddComponent<AccelByteNetworkTransportManager>();
ApiClient apiClient = AccelByteSDK.GetClientRegistry().GetApi();
transportManager.Initialize(apiClient);
}

To set up the network transport, the SetP2PNetworkTransport function is used. In this function, the AccelByteNetworkTransportManager initializes and it is used as a network transport to establish a P2P connection. You need the match session ID in the connection data.

private static void SetP2PNetworkTransport(InGameMode gameMode, string matchSessionId)
{
Init();
InitialConnectionData data = new InitialConnectionData() { inGameMode = gameMode, serverSessionId = matchSessionId };
networkManager.NetworkConfig.ConnectionData = GameUtility.ToByteArray(data);
networkManager.NetworkConfig.NetworkTransport = transportManager;
}

To start as a P2P host, the StartAsHost function is used. This function will start the network manager that has been set up with the in-game mode and match session ID. Then, it starts the network manager as a host.

public static async void StartAsHost(InGameMode gameMode, string matchSessionId)
{
await GameManager.ShowTravelingLoading();

GameManager.Instance.ResetCache();
GameData.ServerType = ServerType.OnlinePeer2Peer;

SetP2PNetworkTransport(gameMode, matchSessionId);
networkManager.StartHost();
BytewarsLogger.Log($"Start P2P Host");
GameManager.StartListenNetworkSceneEvent();
}

To start as a client a P2P network, the StartAsP2PClient function is used. This function needs the host user ID, which you will get from the game session.

public static async void StartAsP2PClient(string hostUserId, InGameMode gameMode, string matchSessionId)
{
await GameManager.ShowTravelingLoading();

GameManager.Instance.ResetCache();
GameData.ServerType = ServerType.OnlinePeer2Peer;

SetP2PNetworkTransport(gameMode, matchSessionId);
transportManager.SetTargetHostUserId(hostUserId);
networkManager.StartClient();
BytewarsLogger.Log($"Start P2P Client hostUserId: {hostUserId}");
}

There is also a file called MatchSessionWrapper.cs. This file has the CreateMatchSession function that will create a match session by performing a set of operations, such as getting the game session configuration, binding the leave session event, and creating a game session by calling CreateSession. You will use the CreateMatchSession method from the MatchSessionWrapper.cs class. MatchSessionWrapper.cs is located in Assets/Resources/Modules/MatchSession/Scripts/MatchSessionWrapper.cs.

protected internal void CreateMatchSession(InGameMode inGameMode, GameSessionServerType sessionServerType)
{
GameManager.Instance.OnClientLeaveSession += LeaveCurrentGameSession;
GameManager.OnDisconnectedInMainMenu += DisconnectFromServer;
lobby.SessionV2GameSessionMemberChanged += OnV2GameSessionMemberChanged;

SelectedGameMode = inGameMode;
ConnectionHandler.Initialization();

Dictionary<InGameMode,
Dictionary<GameSessionServerType,
SessionV2GameSessionCreateRequest>> gameSessionConfig = GameSessionConfig.SessionCreateRequest;

if (!gameSessionConfig.TryGetValue(inGameMode, out var matchTypeDict))
{
BytewarsLogger.LogWarning($"GameSession Configuration not found");
return;
}

if (!matchTypeDict.TryGetValue(sessionServerType, out var request))
{
BytewarsLogger.LogWarning($"Matchtype not found");
return;
}

request.attributes = CreateMatchConfig.CreatedMatchSessionAttribute;

if (ConnectionHandler.IsUsingLocalDS())
{
request.serverName = ConnectionHandler.LocalServerName;
}

// Add preferred regions.
string[] preferredRegions = RegionPreferencesHelper.GetEnabledRegions().Select(x => x.RegionCode).ToArray();
if (preferredRegions.Length > 0)
{
request.requestedRegions = preferredRegions;
}

// Playing with Party additional code
if (!string.IsNullOrEmpty(PartyHelper.CurrentPartyId))
{
string[] memberIds = PartyHelper.PartyMembersData.Select(data => data.UserId).ToArray();

request.teams = new SessionV2TeamData[]
{
new SessionV2TeamData()
{
userIds = memberIds
}
};
}

CreateSession(request);
}

What's in the starter pack

A C# script to create match sessions using dedicated servers has been prepared for you. You will add additional code to it so it can connect to the AGS Game SDK for Unity. The script is called MatchSessionP2PWrapper_Starter.cs and is located in Assets/Resources/Modules/MatchSessionP2P/Scripts/MatchSessionP2PWrapper_Starter.cs.

Implement create match session

In this section, you will implement the AGS Game SDK for Unity API call to create a match session. This MatchSessionP2PWrapper_Starter class is a subclass of MatchSessionWrapper.

  1. First, you need to update BindMatchSessionP2PEvents. You have OnCreateMatchSessionP2P, which is called from MatchSessionWrapper right after a match session is created. You also bind OnJoinMatchSessionP2P, OnCreateMatchCancelled and OnLeaveSessionCompleted in this function.

    protected internal void BindMatchSessionP2PEvents()
    {
    OnCreateMatchSessionP2P += StartP2PHost;
    OnJoinMatchSessionP2P += StartP2PClient;
    OnCreateMatchCancelled += UnbindMatchSessionP2PEvents;
    OnLeaveSessionCompleted += UnbindMatchSessionP2PEvents;
    }
  2. Update UnbindMatchSessionP2PEvents function to remove all event listeners that were set up in BindMatchSessionP2PEvents.

    protected internal void UnbindMatchSessionP2PEvents()
    {
    OnCreateMatchSessionP2P -= StartP2PHost;
    OnJoinMatchSessionP2P -= StartP2PClient;
    OnCreateMatchCancelled -= UnbindMatchSessionP2PEvents;
    OnLeaveSessionCompleted -= UnbindMatchSessionP2PEvents;
    }
  3. In the StartP2PHost function, you use the P2PHelper.StartAsHost function. Update the function with the following code:

    private void StartP2PHost(InGameMode gameMode, Result<SessionV2GameSession> result)
    {
    GameData.ServerSessionID = result.Value.id;
    P2PHelper.StartAsHost(gameMode, result.Value.id);
    }
  4. Similar with the step before, you need to use the P2PHelper.StartP2PClient function and pass the leader ID from the game session to the StartAsP2PClient function. Modify the function using this code:

    private void StartP2PClient(InGameMode gameMode, Result<SessionV2GameSession> result)
    {
    P2PHelper.StartAsP2PClient(result.Value.leaderId, gameMode, result.Value.id);
    }

Resources