public override void OnClientAuthenticate() { IUser[] users = User.GetUsers(); foreach (IUser user in users) { try { user.ClientStartAuthentication(); } catch (Exception ex) { Logger.Error(ex, "An error occured while trying to authenticate on the client end!"); ClientReject(); return; } } Logger.Debug("Sent a total of {Num} of user accounts to the server.", users.Length); NetworkClient.connection.Send(new JoinRequestMessage { ApplicationVersion = Application.version, UserAccounts = users }); }
private void PlayTween(TweenEvent tweenEvent) { //For UI tween event if (tweenEvent is UITweenEvent uiTweenEvent) { objectToTween.SetActive(true); //If this is a moving tween event if (uiTweenEvent.moving) { Tween <float> moveTween = objectToTween.TweenAnchoredPositionY(uiTweenEvent.moveTo, uiTweenEvent.duration); moveTween.SetFrom(uiTweenEvent.moveFrom); moveTween.SetOnComplete(() => OnEnd(uiTweenEvent.activeOnEnd)); } //This is a fading tween event if (uiTweenEvent.fading) { Tween <float> fadeTween = objectToTween.GetComponent <Graphic>() .TweenGraphicAlpha(uiTweenEvent.fadeTo, uiTweenEvent.duration); fadeTween.SetFrom(uiTweenEvent.fadeFrom); fadeTween.SetOnComplete(() => OnEnd(uiTweenEvent.activeOnEnd)); } } else { Logger.Error("Unsupported tween event type!"); } if (!Game.IsGameQuitting) { Logger.Debug("Played event {@Event}", tweenEvent.name); } }
public static void DamageCommandCommand(string[] args) { if (Instance == null) { Logger.Error("A game isn't currently running!"); return; } if (NetworkManager.singleton.mode != NetworkManagerMode.ServerOnly) { Logger.Error("You can only run this command on a server!"); return; } string playerId = args[0]; PlayerManager player = GetPlayer(playerId); if (player == null) { Logger.Error("A player with that ID doesn't exist!"); return; } string damage = args[1]; if (int.TryParse(damage, out int result)) { player.TakeDamage(result, playerId); } else { Logger.Error("The imputed damage to do isn't a number!"); } }
private void RpcClientRespawn() { try { //Enable game objects foreach (GameObject toEnable in disableGameObjectsOnDeath) { toEnable.SetActive(true); } //Enable movement playerMovementManager.enabled = true; //Enable the collider, or the Char controller if (isLocalPlayer) { //Enable our HUD uiManager.SetHud(true); uiManager.SetDeathScreen(null, false); } } catch (Exception ex) { Logger.Error(ex, "Something went wrong in {MethodName}!", nameof(RpcClientRespawn)); } }
/// <summary> /// Start Steam game server /// </summary> /// <param name="onFail"></param> internal static void StartServer(Action onFail) { SteamServerInit serverInit = new("Team-Capture", "Team-Capture") { DedicatedServer = true, Secure = true, VersionString = Application.version, IpAddress = IPAddress.Any, GamePort = 7777 }; authResults = new Dictionary <SteamUser, AuthResult>(); SteamServer.OnSteamServersConnected += () => Logger.Info("Server has connected to Steam game servers."); SteamServer.OnSteamServerConnectFailure += (result, retry) => OnSteamConnectFail(result, onFail); SteamServer.OnValidateAuthTicketResponse += OnAuthResponse; try { SteamServer.Init(SteamManager.Instance.SteamSettings.appDedicatedServerId, serverInit); SteamServer.LogOnAnonymous(); IsOnline = true; } catch (Exception ex) { Logger.Error(ex, "Something went wrong while starting the steam game server integration!"); IsOnline = false; onFail.Invoke(); } }
private static async UniTaskVoid DisplayMotdAndOrCreatePlayer() { await UniTask.WaitUntil(() => clientReceivedConfig); //If the server has an MOTD, display it before creating a player object if (netManager.serverConfig.motdMode != Server.ServerMOTDMode.Disabled && ClientMotdMode != ClientMOTDMode.Disable) { if (netManager.serverConfig.motdMode == Server.ServerMOTDMode.WebOnly && ClientMotdMode == ClientMOTDMode.TextOnly) { RequestPlayerObject(); return; } try { MOTDUI motdUILogic = Object.Instantiate(netManager.motdUIPrefab).GetComponent <MOTDUI>(); motdUILogic.Setup(netManager.serverConfig, RequestPlayerObject); return; } catch (InvalidMOTDSettings ex) { Logger.Error(ex, "Something was wrong with the server's MOTD settings!"); netManager.StopHost(); return; } } RequestPlayerObject(); }
private void RpcClientRespawn() { try { //Enable game objects foreach (GameObject toEnable in disableGameObjectsOnDeath) { toEnable.SetActive(true); } //Enable movement characterController.enabled = true; playerMovementManager.enabled = true; //Enable the collider, or the Char controller if (isLocalPlayer) { //Switch cams GameManager.GetActiveSceneCamera().SetActive(false); //Enable our HUD uiManager.SetHud(true); } playerMovementManager.EnableStateHandling(); } catch (Exception ex) { Logger.Error(ex, "Something went wrong in {MethodName}!", nameof(RpcClientRespawn)); } }
/// <summary> /// Finds all static methods with the <see cref="ConCommand" /> attribute attached to it /// and adds it to the list of commands /// </summary> private static void RegisterCommands() { foreach (KeyValuePair <ConCommand, MethodInfo> command in GetConCommands()) { ConCommand attribute = command.Key; //Create the MethodDelegate from the ConCommand's method MethodDelegate methodDelegate; try { methodDelegate = (MethodDelegate)Delegate.CreateDelegate(typeof(MethodDelegate), command.Value); } catch (Exception ex) { Logger.Error(ex, "An error occurred while adding the command {@Command}'s method!", attribute.Name); continue; } //Add the command AddCommand(new ConsoleCommand { CommandSummary = attribute.Summary, RunPermission = attribute.RunPermission, MinArgs = attribute.MinArguments, MaxArgs = attribute.MaxArguments, CommandMethod = methodDelegate }, attribute.Name); } }
/// <summary> /// Creates a new server process and connects this process to it /// </summary> /// <param name="workingNetManager"></param> /// <param name="gameName"></param> /// <param name="sceneName"></param> /// <param name="maxPlayers"></param> /// <param name="onFailedToStart"></param> internal static void CreateServerAndConnectToServer(this NetworkManager workingNetManager, string gameName, string sceneName, int maxPlayers, Action onFailedToStart = null) { #if UNITY_EDITOR string serverOnlinePath = $"{Voltstro.UnityBuilder.Build.GameBuilder.GetBuildDirectory()}Team-Capture-Quick/{ServerOnlineFile}"; #else string serverOnlinePath = $"{Game.GetGameExecutePath()}/{ServerOnlineFile}"; #endif //Check to make sure the server online file doesn't already exist if (File.Exists(serverOnlinePath)) { Logger.Error("A server is already running!"); return; } //Create and start the process Process newTcServer = new Process { StartInfo = GetTCProcessStartInfo(gameName, sceneName, maxPlayers) }; newTcServer.Start(); //We need to wait for the server online file, and to not cause the game to freeze we run it async WaitForServerOneFileAndConnect(serverOnlinePath, () => { //Start the client workingNetManager.networkAddress = "localhost"; workingNetManager.StartClient(); }, onFailedToStart).Forget(); }
public void Init() { Debug.unityLogger.logEnabled = false; //Attempt to alloc a console for us if (!AllocConsole()) { Logger.Error("Failed to allocate a windows console!"); Game.QuitGame(); } SetConsoleTitle(consoleTitle); //Setup our console streams System.Console.SetOut(new StreamWriter(System.Console.OpenStandardOutput()) { AutoFlush = true }); InitializeInStream(); //Start input system isRunning = true; _ = Task.Run(HandleInputs); Logger.Info("Started Windows command line console."); }
protected override TCServerResponse ProcessRequest(TCServerRequest request, IPEndPoint endpoint) { Logger.Debug("Processing discovery request from `{Address}`...", endpoint.Address); try { if (request.ApplicationVersion != Application.version) { return(null); } return(new TCServerResponse { GameName = TCNetworkManager.Instance.serverConfig.gameName, MaxPlayers = netManager.maxConnections, CurrentAmountOfPlayers = netManager.numPlayers, SceneName = TCScenesManager.GetActiveScene().name }); } catch (NotImplementedException) { Logger.Error("Current transport does not support network discovery!"); throw; } }
/// <summary> /// Call this when the server is stopped /// </summary> internal static void OnStopServer() { Logger.Info("Stopping server..."); PingManager.ServerShutdown(); //Stop advertising the server when the server stops netManager.gameDiscovery.StopDiscovery(); Logger.Info("Server stopped!"); //Close server online file stream try { serverOnlineFileStream.Close(); serverOnlineFileStream.Dispose(); serverOnlineFileStream = null; } catch (Exception ex) { Logger.Error(ex, "An error occurred while shutting down the server!"); } netManager = null; //Double check that the file is deleted if (File.Exists(serverOnlineFilePath)) { File.Delete(serverOnlineFilePath); } }
private static void OnReceivedServerConfig(NetworkConnection conn, ServerConfig config) { //Server has sent config twice in the same scene session? Probs a modified server if (clientHasPlayer) { Logger.Error("The server has sent it's config twice in the same scene session!"); return; } //Set the game name netManager.serverConfig = config; ClientMotdMode = GameSettings.MultiplayerSettings.MOTDMode; //If the server has an MOTD, display it before creating a player object if (config.motdMode != Server.ServerMOTDMode.Disabled && ClientMotdMode != ClientMOTDMode.Disable) { try { MOTDUI motdUILogic = Object.Instantiate(netManager.motdUIPrefab).GetComponent <MOTDUI>(); motdUILogic.Setup(config, () => RequestPlayerObject(conn)); return; } catch (InvalidMOTDSettings ex) { Logger.Error(ex, "Something was wrong with the server's MOTD settings!"); netManager.StopHost(); return; } } RequestPlayerObject(conn); }
/// <summary> /// Toggles between panels /// </summary> /// <param name="panelName"></param> public void TogglePanel(string panelName) { MainMenuPanel panel = GetMenuPanel(panelName); if (panel == null) { Logger.Error("No such panel with the name of {@PanelName}!", name); return; } //There is a panel that is currently active, so close it if (GetActivePanel() != null && panel != GetActivePanel()) { Logger.Debug($"{GetActivePanel().name} is currently active, switching..."); ClosePanel(GetActivePanel(), true); OpenPanel(panel, true); return; } if (!panel.isOpen) { OpenPanel(panel); } else { ClosePanel(panel); } }
private void RpcClientPlayerDie(string killerPlayer) { try { //Disable the collider, or the Char controller if (isLocalPlayer) { //Disable the HUD uiManager.SetHud(false); uiManager.SetDeathScreen(GameManager.GetPlayer(killerPlayer), true); } //Disable movement playerMovementManager.enabled = false; foreach (GameObject toDisable in disableGameObjectsOnDeath) { toDisable.SetActive(false); } } catch (Exception ex) { Logger.Error(ex, "Something went wrong in {MethodName}!", nameof(RpcClientPlayerDie)); } }
private void Awake() { rb = GetComponent <Rigidbody>(); if (rb == null) { Logger.Error("Rocket doesn't have a rigidbody attached to it!"); } }
private static void OnSteamConnectFail(Result result, Action onFail) { Logger.Error("Failed to connect to Steam game servers! Result: {Result}", result); SteamServer.LogOff(); //ShutdownServer(); onFail.Invoke(); }
private void Initialize() { if (client != null) { Logger.Error("The discord client is already running!"); return; } try { client = new global::Discord.GameSDK.Discord(long.Parse(Settings.clientId), CreateFlags.NoRequireDiscord); client.Init(); } catch (ResultException ex) { Logger.Error("Failed to connect with Discord! {@Message} {@ResultCode}", ex.Message, ex.Result); client = null; Destroy(gameObject); return; } client?.SetLogHook(Settings.logLevel, (level, message) => { switch (level) { case LogLevel.Error: Logger.Error(message); break; case LogLevel.Warn: Logger.Warn(message); break; case LogLevel.Info: Logger.Info(message); break; case LogLevel.Debug: Logger.Debug(message); break; default: throw new ArgumentOutOfRangeException(nameof(level), level, null); } }); activityManager = client?.GetActivityManager(); userManager = client?.GetUserManager(); TCScenesManager.PreparingSceneLoadEvent += PreparingSceneLoad; TCScenesManager.OnSceneLoadedEvent += SceneLoaded; SceneLoaded(TCScenesManager.GetActiveScene()); }
public static void ManualExceptionAsyncCommand(string[] args) { try { FailingMethodAsync().GetAwaiter().GetResult(); } catch (Exception ex) { Logger.Error(ex, "Manual exception thrown!"); } }
/// <summary> /// Creates a new server process /// </summary> /// <param name="workingNetManager"></param> /// <param name="gameName"></param> /// <param name="sceneName"></param> /// <param name="maxPlayers"></param> /// <param name="userProvider"></param> /// <param name="shutOnDisconnect"></param> /// <param name="onServerStarted"></param> /// <param name="onServerFailedToStart"></param> internal static void CreateServerProcess(this NetworkManager workingNetManager, string gameName, string sceneName, int maxPlayers, UserProvider userProvider, bool shutOnDisconnect, Action onServerStarted, Action onServerFailedToStart = null) { #if UNITY_EDITOR string serverOnlinePath = $"{GameBuilder.GetBuildDirectory()}Team-Capture-Quick/{ServerOnlineFile}"; #else string serverOnlinePath = $"{Game.GetGameExecutePath()}/{ServerOnlineFile}"; #endif //Check to make sure the server online file doesn't already exist if (File.Exists(serverOnlinePath)) { onServerFailedToStart?.Invoke(); Logger.Error("A server is already running!"); return; } #if UNITY_EDITOR string tcApp = $"{GameBuilder.GetBuildDirectory()}Team-Capture-Quick/"; #else string tcApp = Game.GetGameExecutePath(); #endif #if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN tcApp += "/Team-Capture.exe"; #else tcApp += "/Team-Capture"; #endif string tcArguments = $"-batchmode -nographics -gamename \"{gameName}\" -scene {sceneName} -maxplayers {maxPlayers} -auth-method {userProvider.ToString()}" + $"{(shutOnDisconnect ? " -closeserveronfirstclientdisconnect" : string.Empty)} -high"; #if UNITY_EDITOR_LINUX || UNITY_STANDALONE_LINUX ProcessHelper.LaunchLinuxTerminalAndLaunchProcess(tcApp, tcArguments); #else System.Diagnostics.Process tcProcess = new() { StartInfo = new System.Diagnostics.ProcessStartInfo { FileName = tcApp, Arguments = tcArguments, WorkingDirectory = Game.GetGameExecutePath() } }; tcProcess.Start(); #endif //We need to wait for the server online file, and to not cause the game to freeze we run it async WaitForServerOnlineFile(serverOnlinePath, onServerStarted, onServerFailedToStart).Forget(); }
public static void SetRenderScaleCommand(string[] args) { if (float.TryParse(args[0], out float result)) { GameSettings.AdvSettings.RenderScale = result; GameSettings.Save(); return; } Logger.Error("Invalid input!"); }
public static void SetRefreshRateCommand(string[] args) { if (int.TryParse(args[0], out int refreshRate)) { GameSettings.VideoSettings.Resolution.refreshRate = refreshRate; GameSettings.Save(); return; } Logger.Error("Invalid input!"); }
public static void SetHdrCommand(string[] args) { if (bool.TryParse(args[0], out bool result)) { GameSettings.AdvSettings.HDR = result; GameSettings.Save(); return; } Logger.Error("Invalid input!"); }
public static void CameraFovCommand(string[] args) { if (int.TryParse(args[0], out int cameraFov)) { GameSettings.AdvSettings.CameraFOV = cameraFov; GameSettings.Save(); return; } Logger.Error("Invalid input!"); }
public static void SetShadowCascadesCommand(string[] args) { if (int.TryParse(args[0], out int result)) { GameSettings.AdvSettings.ShadowCascades = (ShadowCascadesCount)result; GameSettings.Save(); return; } Logger.Error("Invalid input!"); }
private void Awake() { if (Instance != null) { Logger.Error("There is already an active GameManager running!"); } else { Instance = this; Setup(); } }
public static void SetMsaaQualityCommand(string[] args) { if (int.TryParse(args[0], out int result)) { GameSettings.AdvSettings.MsaaQuality = (MSAAQuality)result; GameSettings.Save(); return; } Logger.Error("Invalid input!"); }
/// <summary> /// Gets a tweened object /// </summary> /// <param name="tweenObjectName"></param> /// <returns></returns> public TweenObject GetTweenObject(string tweenObjectName) { TweenObject tweenObject = tweenedObjects.FirstOrDefault(x => x.tweenObjectName == tweenObjectName); if (tweenObject != null) { return(tweenObject); } Logger.Error("The tween object {@TweenObjectName) doesn't exist!", tweenObjectName); return(null); }
/// <summary> /// Plays an event /// </summary> /// <param name="eventName"></param> public void PlayEvent(string eventName) { TweenEvent tweenEvent = eventsToPlay.FirstOrDefault(x => x.name == eventName); if (tweenEvent == null) { Logger.Error("There is no tween event called {EventName} on tween object {ObjectName}!", eventName, objectToTween.name); return; } PlayTween(tweenEvent); }
protected override void SingletonStarted() { //Make sure loadingScenePrefab isn't null if (loadingScenePrefab == null) { Logger.Error("LoadingScenePrefab is null!"); Destroy(gameObject); return; } SceneManager.OnBeginSceneLoading += OnBeginSceneLoading; isSetup = true; }