using Assets.Scripts.Multiplayer; using Netcode.Transports.Facepunch; using Steamworks; using Steamworks.Data; using System; using System.Collections; using System.Collections.Generic; using TMPro; using Unity.Netcode; using Unity.Netcode.Transports.UTP; using UnityEngine; using UnityEngine.UI; public class SteamManager : ZNetworkData { [SerializeField] private Button HostBtn; [SerializeField] private Button JoinBtn; [SerializeField] private TMP_InputField LobbyIdInputField; [SerializeField] private TextMeshProUGUI LobbyID; [SerializeField] private GameObject MainMenu; [SerializeField] private GameObject InLobbyMenu; private void Start() { if (NetworkManager.Singleton == null) return; bool isLocal = NetworkManager.Singleton.NetworkConfig.NetworkTransport is UnityTransport; if (isLocal) Destroy(gameObject); SteamMatchmaking.OnLobbyCreated += LobbyCreated; SteamMatchmaking.OnLobbyEntered += LobbyEntered; SteamFriends.OnGameLobbyJoinRequested += GameLobbyJoinRequested; HostBtn.onClick.AddListener(HostLobby); JoinBtn.onClick.AddListener(JoinLobbyWithID); } private void LobbyCreated(Result result, Lobby lobby) { if (result == Result.OK) { lobby.SetPublic(); lobby.SetJoinable(true); NetworkManager.Singleton.StartHost(); } } private void LobbyEntered(Lobby lobby) { SteamLobbySaver.Instance.currentLobby = lobby; LobbyID.text = lobby.Id.ToString(); MainMenu.SetActive(false); InLobbyMenu.SetActive(true); NetworkManager.Singleton.gameObject.GetComponent().targetSteamId = lobby.Owner.Id; NetworkManager.Singleton.StartClient(); Debug.Log("Entered lobby"); } private async void GameLobbyJoinRequested(Lobby lobby, SteamId id) { await lobby.Join(); } private void OnDisable() { SteamMatchmaking.OnLobbyCreated -= LobbyCreated; SteamMatchmaking.OnLobbyEntered -= LobbyEntered; SteamFriends.OnGameLobbyJoinRequested -= GameLobbyJoinRequested; } public async void HostLobby() { IsServer = true; await SteamMatchmaking.CreateLobbyAsync(4); } public void LeaveLobby() { SteamLobbySaver.Instance.currentLobby?.Leave(); SteamLobbySaver.Instance.currentLobby = null; NetworkManager.Singleton.Shutdown(); UpdateUI(); } public void StartGameServer() { if (!NetworkManager.Singleton.IsHost) return; NetworkManager.Singleton.SceneManager.LoadScene("Multiplayer", UnityEngine.SceneManagement.LoadSceneMode.Single); } private void UpdateUI() { if (SteamLobbySaver.Instance.currentLobby == null) { // Show main menu MainMenu.SetActive(true); InLobbyMenu.SetActive(false); } else { // Show In lobby ui MainMenu.SetActive(false); InLobbyMenu.SetActive(true); } } public async void JoinLobbyWithID() { ulong id; if (!ulong.TryParse(LobbyIdInputField.text, out id)) { return; // If id inputted is not ulong, then return } Lobby[] lobbies = await SteamMatchmaking.LobbyList.WithSlotsAvailable(1).RequestAsync(); foreach (Lobby lobby in lobbies) { if (lobby.Id == id) // If found target lobby, then join { await lobby.Join(); return; } } } }