Lobby Handler

mail@pastecode.io avatar
unknown
csharp
8 days ago
2.7 kB
2
Indexable
Never
using UnityEngine;
using Unity.Services.Lobbies;
using Unity.Services.Lobbies.Models;

public class LobbyHandler : MonoBehaviour
{
    public static LobbyHandler Instance;
    public string LobbyName { get; private set; }
    public string LobbyID { get; private set; }
    public string RoomCode { get; private set; }
    public bool RoomFound { get; private set; } = false;

    void Awake()
    {
        if (Instance == null)
        {
            Instance = this;
            DontDestroyOnLoad(gameObject);
        }

        else
        {
            Destroy(gameObject);
        }
    }

    public async void CreateLobby(string lobbyName = "Lobby")
    {
        try
        {
            int maxPlayers = 2;

            CreateLobbyOptions options = new();
            options.IsPrivate = false;

            Lobby lobby = await Lobbies.Instance.CreateLobbyAsync(lobbyName, maxPlayers, options);

            string retrievedRoomCode = lobby.LobbyCode;

            Debug.Log($"Lobby created, ID: {lobby.Id}");
            Debug.Log($"Room code: {retrievedRoomCode}");

            LobbyName = lobbyName;
            RoomCode = retrievedRoomCode;
            LobbyID = lobby.Id;
        }
        catch (LobbyServiceException e)
        {
            Debug.LogError(e);
        }
    }

    public async void JoinLobby(string roomCode)
    {
        RoomFound = false;

        try
        {
            Debug.Log($"Attempting to join |{roomCode}|");

            Lobby lobby = await Lobbies.Instance.JoinLobbyByCodeAsync(roomCode);

            if (lobby != null)
            {
                RoomFound = true;
                Debug.Log($"Joined lobby {lobby.Id}");
            }

            else
            {
                Debug.Log($"Lobby |{roomCode}| was not found");
            }
        }

        catch (LobbyServiceException e)
        {
            Debug.LogError($"Error joining lobby: {e.Message}");
        }
    }

    public async void QuickJoin()
    {
        Debug.Log($"QuickPlay...");

        try
        {
            QuickJoinLobbyOptions options = new();

            Lobby lobby = await Lobbies.Instance.QuickJoinLobbyAsync(options);
        }

        catch (LobbyServiceException e)
        {
            Debug.Log("Couldn't find a lobby");
            Debug.LogWarning(e);
        }
    }

    public async void DeleteLobby(string lobbyId)
    {
        try
        {
            await Lobbies.Instance.DeleteLobbyAsync(lobbyId);
            Debug.Log($"Deleted lobby {lobbyId}");
        }

        catch (LobbyServiceException e)
        {
            Debug.LogError(e);
        }
    }
}
Leave a Comment