Привет, я разрабатываю приложение, похожее на игру-викторину, с unity, которое включает в себя подбор игроков и мультиплеер особенность. Моя проблема в том, что я установил аутентификацию Firebase, а затем я установил базу данных Firebase Realtime, чтобы игрок, который нажмет кнопку «Пуск», после этого увидит поиск по метке игры, совпадающей с другими игроками, я тестирую теперь с разными устройствами, поэтому, когда игрок 1 нажимает кнопку «Пуск», а затем игрок 2 нажимает кнопку «Пуск», оба они должны перейти на сцену игрового процесса, но в моей ситуации только игрок 2, который может перейти на сцену игрового процесса, и игрок 1 застрял на ней. та же сцена. Я хотел бы знать, в чем здесь проблема, я впервые создаю онлайн-приложение/игру, поэтому у меня не было
Код: Выделить всё
using UnityEngine;
using UnityEngine.SceneManagement;
using Firebase;
using Firebase.Database;
using Firebase.Auth;
using System;
using System.Collections.Generic;
public class MatchmakingManager : MonoBehaviour
{
private DatabaseReference databaseReference;
private FirebaseAuth auth;
private FirebaseUser currentUser;
private bool isMatchmaking = false;
private bool sceneTransitioned = false;
void Start()
{
// Initialize Firebase components
databaseReference = FirebaseDatabase.DefaultInstance.RootReference;
auth = FirebaseAuth.DefaultInstance;
currentUser = auth.CurrentUser;
if (currentUser != null)
{
// Check if the current user is already in matchmaking
CheckMatchmakingStatus();
}
else
{
Debug.LogError("User is not logged in.");
}
}
private void CheckMatchmakingStatus()
{
// Check if the current user is already in matchmaking
databaseReference.Child("matchmaking").Child(currentUser.UserId).GetValueAsync().ContinueWith(task =>
{
if (task.IsCompleted && !task.IsFaulted && !task.IsCanceled)
{
DataSnapshot snapshot = task.Result;
if (snapshot != null && snapshot.Exists)
{
// User is already in matchmaking
isMatchmaking = true;
}
else
{
// User is not in matchmaking
isMatchmaking = false;
}
}
else
{
Debug.LogError("Failed to check matchmaking status: " + task.Exception);
}
});
}
public void StartMatchmaking()
{
if (!isMatchmaking)
{
// Add the current user to matchmaking
databaseReference.Child("matchmaking").Child(currentUser.UserId).SetValueAsync(true).ContinueWith(task =>
{
if (task.IsCompleted && !task.IsFaulted && !task.IsCanceled)
{
// Successfully added to matchmaking
isMatchmaking = true;
// Check for available matches
FindMatch();
}
else
{
Debug.LogError("Failed to start matchmaking: " + task.Exception);
}
});
}
else
{
Debug.LogWarning("User is already in matchmaking.");
}
}
public void CancelMatchmaking()
{
// Remove the player from the matchmaking pool
string playerId = auth.CurrentUser.UserId;
databaseReference.Child("matchmaking").Child(playerId).RemoveValueAsync().ContinueWith(task =>
{
if (task.IsCompleted && !task.IsFaulted && !task.IsCanceled)
{
// Successfully removed from matchmaking
isMatchmaking = false;
}
else
{
Debug.LogError("Failed to cancel matchmaking: " + task.Exception);
}
});
}
private void FindMatch()
{
// Query the database for game rooms with two players
databaseReference.Child("matchmaking").OrderByKey().LimitToFirst(2).GetValueAsync().ContinueWith(task =>
{
if (task.IsCompleted && !task.IsFaulted && !task.IsCanceled)
{
DataSnapshot snapshot = task.Result;
if (snapshot != null && snapshot.HasChildren && snapshot.ChildrenCount == 2)
{
// Found two players, remove them from matchmaking
List playerIds = new List();
foreach (DataSnapshot playerSnapshot in snapshot.Children)
{
string playerId = playerSnapshot.Key;
playerIds.Add(playerId);
}
// Create a game room for the matched players
CreateGameRoom(playerIds[0], playerIds[1]);
}
else
{
// No available matches yet or insufficient players in the queue
Debug.Log("No available matches yet or insufficient players in the queue, continuing waiting...");
}
}
else
{
Debug.LogError("Failed to find a match: " + task.Exception);
}
});
}
private void CreateGameRoom(string player1Id, string player2Id)
{
// Generate a unique ID for the game room
string roomId = databaseReference.Child("gameRooms").Push().Key;
// Create a data structure representing the game room
Dictionary roomData = new Dictionary();
roomData["player1Id"] = player1Id;
roomData["player2Id"] = player2Id;
roomData["status"] = "active"; // You can set initial status to "active" or "waiting" or any other status you prefer
// Set the data in the database under the generated room ID
databaseReference.Child("gameRooms").Child(roomId).SetValueAsync(roomData)
.ContinueWith(task =>
{
if (task.IsCompleted && !task.IsFaulted && !task.IsCanceled)
{
Debug.Log("Game room created successfully!");
// Transition the matched players to the gameplay scene only if it hasn't been done before
if (!sceneTransitioned)
{
sceneTransitioned = true;
SceneManager.LoadScene("GamePlay");
}
}
else if (task.IsFaulted)
{
// Handle the error
foreach (Exception exception in task.Exception.InnerExceptions)
{
Debug.LogError("Failed to create game room: " + exception.Message);
}
}
else if (task.IsCanceled)
{
Debug.LogWarning("Creating game room task was canceled.");
}
else
{
Debug.LogError("Unknown error occurred while creating game room.");
}
});
}
}
i want both of players to go to the gameplay scene after that I'll need to handle the other features like scores,players name etc.
Источник: https://stackoverflow.com/questions/781 ... e-database