top of page

未発表パーティゲーム MultiplayerMenu.cs

  • msandfrey3
  • Aug 12, 2024
  • 4 min read
using UnityEngine;
using Fusion;
using TMPro;
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine.EventSystems;
using PartyGame.UI;
using PartyGame.GameManagement;
using Zenject;
using UnityEngine.SceneManagement;
using PartyGame.Config;
using Fusion.Sockets;
using System;
namespace PartyGame.Multiplayer
{
    public class MultiplayerMenu : MonoBehaviour, INetworkRunnerCallbacks
    {
        private const string TOURNAMENT_SCENE_NAME = "TournamentScene";
        private const int ROOM_CODE_LENGTH = 6;
        private const int PLAYER_COUNT = 4;
        [SerializeField] private NetworkRunner _networkRunnerPrefab;
        [SerializeField] private GameObject _loadingObject;
        [SerializeField] private GameObject _panel;
        [SerializeField] private TMP_InputField _inputField;
        [SerializeField] private TMP_Text _errorText;
        [SerializeField] private TMP_Text _searchText;
        [Header("Buttons")]
        [SerializeField] private LTSButton _defaultSelectedButton;
        [SerializeField] private LTSButton _achievementsButton;
        [SerializeField] private LTSButton _hostButton;
        [SerializeField] private LTSButton _joinButton;
        [SerializeField] private LTSButton _localPlayButton;
        [SerializeField] private LTSButton _settingsButton;
        [SerializeField] private LTSButton _storeButton;
        [SerializeField] private LTSButton _quitButton;
        [SerializeField] private LTSButton _joinCancelButton;
        [Header("Submenus")]
        [SerializeField] private SettingsMenuUI _settingsMenuUI;
        [SerializeField] private GameObject _tutorialScreen;
        [Inject] private SceneLoader _sceneLoader;
        private NetworkRunner _networkRunner;
        private EventSystem _eventSystem;
        private bool _isStarting = false;
        private void Start()
        {
            Application.targetFrameRate = ApplicationConfig.Instance.GameConfig.settings.targetFPS;
            _panel.SetActive(true);
            _loadingObject.SetActive(false);
            _inputField.characterValidation = TMP_InputField.CharacterValidation.Alphanumeric;
            _inputField.onValidateInput += ValidateJoinCode;
            _eventSystem = EventSystem.current;
            _eventSystem.SetSelectedGameObject(_defaultSelectedButton.gameObject);
            _localPlayButton.Initialize(StartOffline);
            _hostButton.Initialize(StartHost);
            _joinButton.Initialize(StartClient);
            _settingsButton.Initialize(OpenSettings);
            _quitButton.Initialize(Application.Quit);
            _storeButton.Initialize(OpenStore);
            _achievementsButton.Initialize(OpenAchievements);
            AudioManager.Instance.PlayMusic(MusicType.MainMenu_BackgroundMusic);
        }
        private void StartHost()
        {
            string roomCode = RoomCode.Create(ROOM_CODE_LENGTH);
            _searchText.text = "Starting game...";
            _joinCancelButton.gameObject.SetActive(false);
            StartGame(GameMode.Host, roomCode);
        }
        private void StartClient()
        {
            string _roomCode = _inputField.text;
            if (_roomCode == null || _roomCode.Length <= 0)
            {
                StartCoroutine(StartRandom());
                return;
            }
            if (_roomCode.Length != ROOM_CODE_LENGTH)
            {
                _errorText.text = "Please enter a room code of length: " + ROOM_CODE_LENGTH;
                return;
            }
            _searchText.text = "Searching for game...";
            _joinCancelButton.gameObject.SetActive(true);
            StartGame(GameMode.Client, _roomCode, true);
        }
        private void StartOffline()
        {
            string roomCode = RoomCode.Create(ROOM_CODE_LENGTH);
            _searchText.text = "Starting game...";
            _joinCancelButton.gameObject.SetActive(false);
            StartGame(GameMode.Single, roomCode);
        }
        private IEnumerator StartRandom()
        {
            _networkRunner = FindObjectOfType<NetworkRunner>();
            if (_networkRunner == null)
            {
                _networkRunner = Instantiate(_networkRunnerPrefab);
            }
            _networkRunner.AddCallbacks(this);
            // Let the Fusion Runner know that we will be providing user input
            _networkRunner.ProvideInput = true;
            _searchText.text = "Searching for game...";
            _panel.SetActive(false);
            _loadingObject.SetActive(true);
            Task<StartGameResult> task = _networkRunner.JoinSessionLobby(SessionLobby.ClientServer);
            while (!task.IsCompleted)
            {
                yield return null;
            }
            StartGameResult result = task.Result;
            if (result.Ok)
            {
                Debug.Log("Successfully joined lobby");
            }
            else
            {
                //error message
                _errorText.text = result.ShutdownReason.ToString();
                _panel.SetActive(true);
                _loadingObject.SetActive(false);
            }
        }
        public void OnSessionListUpdated(NetworkRunner runner, List<SessionInfo> sessionList)
        {
            Debug.Log($"Session List Updated with {sessionList.Count} session(s)");
            if (sessionList.Count == 0)
            {
                return;
            }
            bool isSessionFound = false;
            string session = "";
            string version = Application.version.ToString();
            int i = 0;
            while (!isSessionFound)
            {
                if (sessionList[i].IsOpen && sessionList[i].Properties["Version"] == version)
                {
                    session = sessionList[i].Name;
                    isSessionFound = true;
                }
                else
                {
                    i++;
                    isSessionFound = i >= sessionList.Count;
                }
            }
            if (session == "")
            {
                return;
            }
            _searchText.text = "Joining game...";
            StartGame(GameMode.Client, session, true);
        }
        public void CancelJoin()
        {
            if (_isStarting)
            {
                //things might get messed up if we try to cancel while joining
                return;
            }
            //error message
            _errorText.text = "No games to join";
            _panel.SetActive(true);
            _loadingObject.SetActive(false);
            _networkRunner.RemoveCallbacks(this);
            Destroy(_networkRunner.gameObject);
        }
        /// <summary>
        /// GameMode.Host = Start a session with a specific name
        /// GameMode.Client = Join a session with a specific name
        /// GameMode.Single = Local play only
        /// </summary>
        /// <param name="gameMode"></param>
        private void StartGame(GameMode gameMode, string roomCode, bool disableClientSessionCreation = false)
        {
            _isStarting = true;
            _joinCancelButton.gameObject.SetActive(false);
            //need a runner to do anything with fusion, so if 
            //there isn't one, make one
            _networkRunner = FindObjectOfType<NetworkRunner>();
            if (_networkRunner == null)
            {
                _networkRunner = Instantiate(_networkRunnerPrefab);
            }
            // Let the Fusion Runner know that we will be providing user input
            _networkRunner.ProvideInput = true;
            _networkRunner.RemoveCallbacks(this);
            Dictionary<string, SessionProperty> properties = new();
            properties.Add("Version", Application.version.ToString());
            StartGameArgs startGameArgs = new StartGameArgs()
            {
                GameMode = gameMode,
                SessionName = roomCode,
                PlayerCount = PLAYER_COUNT,
                DisableClientSessionCreation = disableClientSessionCreation,
                SessionProperties = properties
            };
            //need something to explain unable to connect
            StartCoroutine(AttemptStartGame(startGameArgs));
        }
        private IEnumerator AttemptStartGame(StartGameArgs startGameArgs)
        {
            _panel.SetActive(false);
            _loadingObject.SetActive(true);
            Task<StartGameResult> task = _networkRunner.StartGame(startGameArgs);
            while (!task.IsCompleted)
            {
                yield return null;
            }
            StartGameResult result = task.Result;
            if (result.Ok)
            {
                yield return ShowTutoritalScreen(5.0f);
                int tournamentSceneIndex = FindSceneBuildIndex(TOURNAMENT_SCENE_NAME);
                _networkRunner.SetActiveScene(tournamentSceneIndex);
            }
            else
            {
                //error message
                _errorText.text = result.ShutdownReason.ToString();
                _panel.SetActive(true);
                _loadingObject.SetActive(false);
                Destroy(_networkRunner.gameObject);
            }
        }
        private IEnumerator ShowTutoritalScreen(float time)
        {
            _tutorialScreen.SetActive(true);
            yield return new WaitForSeconds(time);
        }
        private void OpenSettings()
        {
            _settingsMenuUI.Show();
        }
        private void OpenStore()
        {
            throw new System.Exception("Not implemented");
        }
        private void OpenAchievements()
        {
            throw new System.Exception("Not implemented");
        }
        private char ValidateJoinCode(string text, int charIndex, char character)
        {
            if (text.Length >= ROOM_CODE_LENGTH)
            {
                return '\0';
            }
            character = char.IsLetter(character) ? char.ToUpper(character) : character;
            return character;
        }
        private int FindSceneBuildIndex(string sceneName)
        {
            int sceneCount = SceneManager.sceneCountInBuildSettings;
            for (int i = 0; i < sceneCount; i++)
            {
                string path = SceneUtility.GetScenePathByBuildIndex(i);
                if (path.Contains(sceneName))
                {
                    return i;
                }
            }
            return -1;
        }
        public void OnPlayerJoined(NetworkRunner runner, PlayerRef player)
        {
            throw new NotImplementedException();
        }
        public void OnPlayerLeft(NetworkRunner runner, PlayerRef player)
        {
            throw new NotImplementedException();
        }
        public void OnInput(NetworkRunner runner, NetworkInput input)
        {
            throw new NotImplementedException();
        }
        public void OnInputMissing(NetworkRunner runner, PlayerRef player, NetworkInput input)
        {
            throw new NotImplementedException();
        }
        public void OnShutdown(NetworkRunner runner, ShutdownReason shutdownReason)
        {
            Debug.Log("Shutting down network Runner.");
        }
        public void OnConnectedToServer(NetworkRunner runner)
        {
            throw new NotImplementedException();
        }
        public void OnDisconnectedFromServer(NetworkRunner runner)
        {
            throw new NotImplementedException();
        }
        public void OnConnectRequest(NetworkRunner runner, NetworkRunnerCallbackArgs.ConnectRequest request, byte[] token)
        {
            throw new NotImplementedException();
        }
        public void OnConnectFailed(NetworkRunner runner, NetAddress remoteAddress, NetConnectFailedReason reason)
        {
            throw new NotImplementedException();
        }
        public void OnUserSimulationMessage(NetworkRunner runner, SimulationMessagePtr message)
        {
            throw new NotImplementedException();
        }
        public void OnCustomAuthenticationResponse(NetworkRunner runner, Dictionary<string, object> data)
        {
            throw new NotImplementedException();
        }
        public void OnHostMigration(NetworkRunner runner, HostMigrationToken hostMigrationToken)
        {
            throw new NotImplementedException();
        }
        public void OnReliableDataReceived(NetworkRunner runner, PlayerRef player, ArraySegment<byte> data)
        {
            throw new NotImplementedException();
        }
        public void OnSceneLoadDone(NetworkRunner runner)
        {
            throw new NotImplementedException();
        }
        public void OnSceneLoadStart(NetworkRunner runner)
        {
            throw new NotImplementedException();
        }
    }
}

Recent Posts

See All

Comments


© 2024 by Matthew Sandfrey. Proudly created with Wix.com

bottom of page