using System.Collections; using System.Collections.Generic; using TMPro; using Unity.Netcode.Transports.UTP; using Unity.Netcode; using Unity.Networking.Transport.Relay; using Unity.Services.Relay.Models; using Unity.Services.Relay; using UnityEngine; using Unity.Services.Authentication; using Unity.Services.Core; using Unity.Services.Lobbies.Models; using Unity.Services.Lobbies; public class Server : MonoBehaviour { [SerializeField] private RS_Button button; [SerializeField] private string lobbyName; [SerializeField] private int maxPlayers; private float heartbeatTimer = 10f; private Lobby hostLobby; private async void Start() { await UnityServices.InitializeAsync(); AuthenticationService.Instance.SignedIn += () => { Debug.Log("Server Launched. " + AuthenticationService.Instance.PlayerId); }; await AuthenticationService.Instance.SignInAnonymouslyAsync(); } private void Update() { HandleLobbyHeartbeat(); } private async void HandleLobbyHeartbeat() { if (hostLobby != null) { heartbeatTimer -= Time.deltaTime; if (heartbeatTimer < 0f) { float heartbeatTimerMax = 15f; heartbeatTimer = heartbeatTimerMax; await LobbyService.Instance.SendHeartbeatPingAsync(hostLobby.Id); } } } public async void RunServer() { try { button.Button.enabled = false; Allocation allocation = await RelayService.Instance.CreateAllocationAsync(maxPlayers); string joinCode = await RelayService.Instance.GetJoinCodeAsync(allocation.AllocationId); CreateLobbyOptions options = new CreateLobbyOptions { IsPrivate = false, Data = new Dictionary { { "joinCode", new DataObject(DataObject.VisibilityOptions.Member, joinCode) } } }; hostLobby = await LobbyService.Instance.CreateLobbyAsync(lobbyName, maxPlayers, options); Debug.Log(joinCode); RelayServerData relayServerData = new RelayServerData(allocation, "dtls"); NetworkManager.Singleton.GetComponent().SetRelayServerData(relayServerData); NetworkManager.Singleton.StartServer(); } catch (RelayServiceException ex) { Debug.Log(ex); button.Button.enabled = true; } } }