### Performing Web Requests with NetWebRequests C# Source: https://github.com/aevien/master-server-toolkit/blob/master/Docs/Tools/Utilities.md Provides examples of using the NetWebRequests class for common HTTP operations like GET and POST requests, and specifically for downloading textures. It demonstrates handling responses via callbacks. ```C# // Отправка GET-запроса NetWebRequests.Get("https://api.example.com/data", (success, response) => { if (success) { // Обработка ответа Debug.Log(response); } }); // Отправка POST-запроса var data = new Dictionary { { "username", "player1" }, { "score", "100" } }; NetWebRequests.Post("https://api.example.com/scores", data, (success, response) => { if (success) { Debug.Log("Score submitted"); } }); // Загрузка текстуры NetWebRequests.GetTexture("https://example.com/image.jpg", (success, texture) => { if (success) { // Использование текстуры profileImage.texture = texture; } }); ``` -------------------------------- ### Creating Serializable Key-Value Pairs C# Source: https://github.com/aevien/master-server-toolkit/blob/master/Docs/Tools/Utilities.md Illustrates how to create a serializable key-value pair class (StringIntPair) inheriting from SerializedKeyValuePair for use in the Unity Inspector. It shows an example of using a list of these pairs in a MonoBehaviour. ```C# // Сериализуемая пара ключ-значение для использования в инспекторе Unity [Serializable] public class StringIntPair : SerializedKeyValuePair { } public class InventoryManager : MonoBehaviour { [SerializeField] private List startingItems = new List(); private void Start() { foreach (var item in startingItems) { AddItem(item.Key, item.Value); } } private void AddItem(string itemId, int count) { // Реализация } } ``` -------------------------------- ### Example Localization Key Naming Best Practice Text Source: https://github.com/aevien/master-server-toolkit/blob/master/Docs/Core/Localization.md Provides examples of structured localization keys using namespaces (e.g., `ui_`, `game_`, `error_`) to organize keys logically based on their usage context within the application. ```Text ui_main_menu_title ui_settings_volume game_message_victory error_network_timeout ``` -------------------------------- ### Implementing a Game Manager Singleton C# Source: https://github.com/aevien/master-server-toolkit/blob/master/Docs/Tools/Utilities.md Demonstrates creating a game manager using GlobalDynamicSingletonBehaviour, managing game states, and loading scenes asynchronously using ScenesLoader. It shows how to access the singleton instance and trigger state changes or level loading. ```C# public class GameManager : GlobalDynamicSingletonBehaviour { // Состояние игры public GameState CurrentState { get; private set; } // События public event Action OnGameStateChanged; // Изменение состояния игры public void ChangeState(GameState newState) { CurrentState = newState; OnGameStateChanged?.Invoke(newState); } // Загрузка нового уровня public void LoadLevel(int levelIndex) { ChangeState(GameState.Loading); ScenesLoader.LoadSceneAsync($"Level_{levelIndex}", (progress) => { // Обновление прогресса }, () => { ChangeState(GameState.Playing); }); } } // Использование GameManager.Instance.LoadLevel(1); ``` -------------------------------- ### Opening URLs with MstWebBrowser C# Source: https://github.com/aevien/master-server-toolkit/blob/master/Docs/Tools/Utilities.md Shows how to use the MstWebBrowser class to open web pages or local files in the default system browser. It includes checking if opening URLs is supported before attempting the action. ```C# // Открытие URL во внешнем браузере MstWebBrowser.OpenURL("https://example.com"); // Открытие URL с проверкой поддержки if (MstWebBrowser.CanOpenURL) { MstWebBrowser.OpenURL("https://example.com"); } // Открытие локального HTML-файла MstWebBrowser.OpenLocalFile("Documentation.html"); ``` -------------------------------- ### Example Long Text Localization Key Config Source: https://github.com/aevien/master-server-toolkit/blob/master/Docs/Core/Localization.md Shows how to define a localization key for longer text passages, such as tutorial steps or descriptions, in the localization file format. ```Config # tutorial_step1;Press [WASD] to move;Нажмите [WASD] для передвижения;... ``` -------------------------------- ### Implementing an Object Pooling System C# Source: https://github.com/aevien/master-server-toolkit/blob/master/Docs/Tools/Utilities.md Shows how to create a generic object pooling system for effects using SingletonBehaviour and GenericPool. It demonstrates initializing pools from serialized data, spawning objects, and returning them to the pool, including a coroutine for delayed return. ```C# public class EffectsPool : SingletonBehaviour { [Serializable] public class EffectPoolData { public string effectId; public GameObject prefab; public int initialSize; } [SerializeField] private List effectsData; private Dictionary> effectPools = new Dictionary>(); protected override void Awake() { base.Awake(); // Инициализация пулов foreach (var data in effectsData) { var pool = new GenericPool(() => Instantiate(data.prefab), data.initialSize); effectPools.Add(data.effectId, pool); } } public GameObject SpawnEffect(string effectId, Vector3 position, Quaternion rotation) { if (effectPools.TryGetValue(effectId, out var pool)) { var effect = pool.Get(); effect.transform.position = position; effect.transform.rotation = rotation; effect.SetActive(true); return effect; } Debug.LogWarning($"Effect {effectId} not found in pools"); return null; } public void ReturnEffect(string effectId, GameObject effect) { if (effectPools.TryGetValue(effectId, out var pool)) { effect.SetActive(false); pool.Return(effect); } } } // Использование void PlayExplosion(Vector3 position) { var effect = EffectsPool.Instance.SpawnEffect("explosion", position, Quaternion.identity); // Автоматический возврат в пул через 2 секунды StartCoroutine(ReturnAfterDelay("explosion", effect, 2f)); } IEnumerator ReturnAfterDelay(string effectId, GameObject effect, float delay) { yield return new WaitForSeconds(delay); EffectsPool.Instance.ReturnEffect(effectId, effect); } ``` -------------------------------- ### Generating Random Names C# Source: https://github.com/aevien/master-server-toolkit/blob/master/Docs/Tools/Utilities.md Demonstrates various methods of the SimpleNameGenerator class for creating random strings, including generating names of a specific length, with a prefix, from syllables, and unique identifiers. ```C# // Генерация случайных имен string randomName = SimpleNameGenerator.Generate(length: 6); // Генерация имени с заданным префиксом string playerName = SimpleNameGenerator.Generate("Player_", 4); // Генерация имени из слогов string nameFromSyllables = SimpleNameGenerator.GenerateFromSyllables(3); // Создание уникального идентификатора string uniqueId = SimpleNameGenerator.GenerateUniqueName(); ``` -------------------------------- ### Use Localized Format Helper C# Source: https://github.com/aevien/master-server-toolkit/blob/master/Docs/Core/Localization.md Shows how to call the `GetLocalizedFormat` helper function with a localization key and arguments (like a player name) to get a localized message string. ```C# string message = GetLocalizedFormat("welcome_player", playerName); ``` -------------------------------- ### Define Game Mode Enum C# Source: https://github.com/aevien/master-server-toolkit/blob/master/Docs/Core/Localization.md Defines a simple C# enumeration `GameMode` with different game types (Single, Multiplayer, Tournament). This enum is used as an example for demonstrating enum localization. ```C# public enum GameMode { Single, Multiplayer, Tournament } ``` -------------------------------- ### Format Localized Strings C# Source: https://github.com/aevien/master-server-toolkit/blob/master/Docs/Core/Localization.md Demonstrates basic string formatting using a localized template retrieved from Mst.Localization. It requires a localization key and arguments to replace placeholders in the template. ```C# string scoreText = string.Format( Mst.Localization["player_score"], currentScore ); ``` -------------------------------- ### Registering Command with Attribute (Direct Args) - C# Source: https://github.com/aevien/master-server-toolkit/blob/master/Assets/MasterServerToolkit/Tools/Terminal/README.md Demonstrates how to register a static C# method as a terminal command using the RegisterCommand attribute. It specifies help text and expected argument counts. The method receives arguments as a CommandArg array, accesses them by index, performs basic error checking, and logs the result using Terminal.Log. ```C# [RegisterCommand(Help = "Adds 2 numbers", MinArgCount = 2, MaxArgCount = 2)] static void CommandAdd(CommandArg[] args) { int a = args[0].Int; int b = args[1].Int; if (Terminal.IssuedError) return; // Error will be handled by Terminal int result = a + b; Terminal.Log("{0} + {1} = {2}", a, b, result); } ``` -------------------------------- ### Apache License 2.0 Boilerplate Notice - Text Source: https://github.com/aevien/master-server-toolkit/blob/master/Assets/MasterServerToolkit/Bridges/Shared/Fonts/Lorenzo Sans/LICENSE.txt This snippet provides the standard boilerplate notice required to be included in files or documentation of works licensed under the Apache License, Version 2.0. Users should replace the bracketed placeholders with their specific information and enclose the text in appropriate comment syntax for the file format. ```Text Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ``` -------------------------------- ### Set Language via Command Line Bash Source: https://github.com/aevien/master-server-toolkit/blob/master/Docs/Core/Localization.md Demonstrates how to pass a default language setting to the application executable (`Game.exe`) using a command line argument (`-defaultLanguage`) in a bash shell. ```Bash ./Game.exe -defaultLanguage ru ``` -------------------------------- ### Manually Adding Command to Shell - C# Source: https://github.com/aevien/master-server-toolkit/blob/master/Assets/MasterServerToolkit/Tools/Terminal/README.md Demonstrates how to manually register a command with the terminal shell. This method is used for non-static methods or when more explicit control over registration is needed. It takes the command name, the delegate for the command method, minimum and maximum argument counts, and help text as parameters. ```C# Terminal.Shell.AddCommand("add", CommandAdd, 2, 2, "Adds 2 numbers"); ``` -------------------------------- ### Create Localized Format Helper C# Source: https://github.com/aevien/master-server-toolkit/blob/master/Docs/Core/Localization.md Provides a static helper function `GetLocalizedFormat` to simplify retrieving and formatting localized strings with variable arguments. It fetches the template by key and applies the arguments. ```C# public static string GetLocalizedFormat(string key, params object[] args) { string template = Mst.Localization[key]; return string.Format(template, args); } ``` -------------------------------- ### Command Logic Method (FrontCommand Pattern) - C# Source: https://github.com/aevien/master-server-toolkit/blob/master/Assets/MasterServerToolkit/Tools/Terminal/README.md This is the core logic method for a command when using the FrontCommand pattern. It receives arguments directly as typed parameters (int a, int b). The argument parsing and error handling are expected to be handled by a separate FrontCommand method. It performs the addition and logs the result. ```C# [RegisterCommand(Help = "Adds 2 numbers")] static void CommandAdd(int a, int b) { int result = a + b; Terminal.Log("{0} + {1} = {2}", a, b, result); } ``` -------------------------------- ### Implement Custom JSON Localization Loader C# Source: https://github.com/aevien/master-server-toolkit/blob/master/Docs/Core/Localization.md Provides C# classes (`CustomLocalizationLoader`, `LocalizationData`, `LocalizationEntry`, `Translation`) and a static method `LoadJson` to load localization data from a custom JSON format, demonstrating how to extend the localization system for different file types. ```C# public class CustomLocalizationLoader { public static void LoadJson(string jsonPath) { var jsonText = Resources.Load(jsonPath).text; var locData = JsonUtility.FromJson(jsonText); foreach (var entry in locData.entries) { foreach (var translation in entry.translations) { Mst.Localization.RegisterKey( translation.lang, entry.key, translation.value ); } } } } [System.Serializable] public class LocalizationData { public LocalizationEntry[] entries; } [System.Serializable] public class LocalizationEntry { public string key; public Translation[] translations; } [System.Serializable] public class Translation { public string lang; public string value; } ``` -------------------------------- ### FrontCommand Argument Parser - C# Source: https://github.com/aevien/master-server-toolkit/blob/master/Assets/MasterServerToolkit/Tools/Terminal/README.md This method serves as the argument parser for a command using the FrontCommand pattern. It receives arguments as a CommandArg array, extracts and converts them to the required types (int a, int b), checks for errors using Terminal.IssuedError, and then calls the main command logic method (CommandAdd) with the parsed arguments. ```C# static void FrontCommandAdd(CommandArg[] args) { int a = args[0].Int; int b = args[1].Int; if (Terminal.IssuedError) return; CommandAdd(a, b); } ``` -------------------------------- ### Handle Localization Events C# Source: https://github.com/aevien/master-server-toolkit/blob/master/Docs/Core/Localization.md Shows how to subscribe to the `Mst.Localization.LanguageChangedEvent` to react when the language changes and how to report missing translations by invoking a custom event (`translationMissing`) via `Mst.Events`. ```C# // Уведомление о смене языка Mst.Localization.LanguageChangedEvent += (lang) => { Mst.Events.Invoke("languageChanged", lang); }; // Уведомление об ошибках перевода public static void ReportMissingTranslation(string key, string lang) { Mst.Events.Invoke("translationMissing", new { key, lang }); Debug.LogWarning($"Missing translation: {key} for {lang}"); } ``` -------------------------------- ### Registering Command with Attribute (Custom Name) - C# Source: https://github.com/aevien/master-server-toolkit/blob/master/Assets/MasterServerToolkit/Tools/Terminal/README.md Shows how to override the default command name inferred from the method name when using the RegisterCommand attribute. By setting the Name property, the command will be invoked using the specified name ("MyAdd" in this case) instead of the method name. ```C# [RegisterCommand(Name = "MyAdd", Help = "Adds 2 numbers", MinArgCount = 2, MaxArgCount = 2)] ``` -------------------------------- ### Define Localized Enum Keys Config Source: https://github.com/aevien/master-server-toolkit/blob/master/Docs/Core/Localization.md Shows the expected format for defining localization keys specifically for enum values in the localization file. The key pattern is typically `enum_EnumTypeName_EnumValueName`. ```Config # enum_GameMode_Single;Single Player;Одиночная игра;Einzelspieler # enum_GameMode_Multiplayer;Multiplayer;Многопользовательская игра;Mehrspieler ``` -------------------------------- ### Create Localized Sprite Component C# Source: https://github.com/aevien/master-server-toolkit/blob/master/Docs/Core/Localization.md Implements a MonoBehaviour component (`LocalizedSprite`) that changes the displayed sprite on an Image component based on the current language. It subscribes to the language change event to update automatically. ```C# public class LocalizedSprite : MonoBehaviour { [Header("Localized Sprites")] public Sprite englishSprite; public Sprite russianSprite; public Sprite germanSprite; private Image imageComponent; void Start() { imageComponent = GetComponent(); Mst.Localization.LanguageChangedEvent += UpdateSprite; UpdateSprite(Mst.Localization.Lang); } void UpdateSprite(string lang) { switch (lang) { case "en": imageComponent.sprite = englishSprite; break; case "ru": imageComponent.sprite = russianSprite; break; case "de": imageComponent.sprite = germanSprite; break; } } } ``` -------------------------------- ### Validate Missing Translations C# Source: https://github.com/aevien/master-server-toolkit/blob/master/Docs/Core/Localization.md Implements a function `ValidateTranslations` to check if a predefined set of required localization keys exists for specific languages, logging warnings if a translation is missing (indicated by the key being returned instead of a translated value). ```C# void ValidateTranslations() { string[] requiredKeys = { "ui_welcome", "btn_ok", "game_start" }; string[] languages = { "en", "ru", "de" }; foreach (var key in requiredKeys) { foreach (var lang in languages) { var oldLang = Mst.Localization.Lang; Mst.Localization.Lang = lang; if (Mst.Localization[key] == key) { Debug.LogWarning($"Missing translation for {key} in {lang}"); } Mst.Localization.Lang = oldLang; } } } ``` -------------------------------- ### Create Localized Enum Helper C# Source: https://github.com/aevien/master-server-toolkit/blob/master/Docs/Core/Localization.md Provides a generic static helper function `GetLocalizedEnum` to retrieve localized strings for enum values. It constructs a localization key based on the enum type name and the specific enum value. ```C# public static string GetLocalizedEnum(T enumValue) where T : Enum { string key = $"enum_{typeof(T).Name}_{enumValue}"; return Mst.Localization[key]; } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.