LobbyCreateOrJoinHandler
unknown
csharp
a year ago
2.7 kB
10
Indexable
using System.Collections.Generic;
using UnityEngine;
using Unity.Services.Lobbies;
using Unity.Services.Lobbies.Models;
public class LobbyCreateOrJoinHandler : MonoBehaviour
{
[SerializeField] SceneTransitionManager _sceneTransitionManager;
string _roomCode;
public async void CreateLobby(string lobbyName)
{
try
{
int maxPlayers = 2;
_roomCode = RoomCodeGenerator.GenerateRoomCode(5);
var options = new CreateLobbyOptions
{
IsPrivate = false,
Data = new Dictionary<string, DataObject>
{
{"roomCode", new DataObject(DataObject.VisibilityOptions.Public, _roomCode)}
},
};
Lobby lobby = await Lobbies.Instance.CreateLobbyAsync(lobbyName, maxPlayers, options);
Debug.Log($"Lobby created {lobby.Id}");
Debug.Log($"Room code {_roomCode}");
//_sceneTransitionManager.LoadSceneTransition(_sceneTransitionManager.Wipe, "LobbyRoom");
}
catch (LobbyServiceException e)
{
Debug.LogError(e);
}
}
public async void JoinLobby(string roomCode)
{
try
{
QueryLobbiesOptions options = new QueryLobbiesOptions
{
Filters = new List<QueryFilter>
{
new QueryFilter(
field: QueryFilter.FieldOptions.S1,
op: QueryFilter.OpOptions.EQ,
value: roomCode)
}
};
QueryResponse queryResponse = await Lobbies.Instance.QueryLobbiesAsync(options);
if (queryResponse.Results.Count > 0)
{
Lobby foundLobby = queryResponse.Results[0];
if (foundLobby.AvailableSlots > 0)
{
Lobby lobby = await Lobbies.Instance.JoinLobbyByCodeAsync(foundLobby.Id);
Debug.Log($"Joined lobby {lobby.Id}");
_sceneTransitionManager.LoadSceneTransition(_sceneTransitionManager.Wipe, "LobbyRoom");
}
else
{
Debug.Log("Lobby is full.");
}
}
else
{
Debug.Log("No lobby found with the given room code.");
}
}
catch (LobbyServiceException e)
{
Debug.LogError(e);
}
}
public string GetRoomCode()
{
return _roomCode;
}
}Editor is loading...
Leave a Comment