### Signaling Gameplay State with PluginYG Source: https://max-games.ru/plugin-yg/doc/index Demonstrates how to signal the start and end of gameplay using PluginYG methods. These methods are important for analytics and for correctly managing game state during ad interruptions or other pauses. ```csharp // Signal that the game is ready for gameplay (if Auto GRA is off): YG2.GameReadyAPI(); // Signal the start of gameplay: YG2.GameplayStart(); // Signal the end of gameplay: YG2.GameplayStop(); // Check if gameplay is active: bool isPlaying = YG2.isGameplaying; ``` -------------------------------- ### Metrica Plugin Setup Source: https://max-games.ru/plugin-yg/doc/metrica Instructions for setting up the Metrica plugin by creating a Yandex Metrica counter and configuring the plugin with the counter ID. ```APIDOC ## Metrica Plugin Setup ### Description Integrate Yandex Metrica by creating a counter on the Yandex Metrica website. Use your game's name as the counter name and `yandex.ru/games/app/012345` as the website address. Copy the counter ID and paste it into the **Metrica Counter ID** field in the plugin settings. ### Parameters #### Request Body - **Metrica Counter ID** (string) - Required - The ID of your Yandex Metrica counter. ``` -------------------------------- ### Managing Game Pause State with PluginYG Source: https://max-games.ru/plugin-yg/doc/index Provides examples of how to control game pausing using PluginYG. This includes methods to pause and resume the game, with options to manage audio, time, cursor, and the Event System. ```csharp // To pause the game: YG2.PauseGame(true); // To resume the game: YG2.PauseGame(false); // Pause without stopping the Event System: YG2.PauseGameNoEditEventSystem(); // Check if the game is paused: bool isPaused = YG2.isPauseGame; ``` -------------------------------- ### Add Option with Activity Flag (C#) Source: https://max-games.ru/plugin-yg/doc/platform/create-platform This example shows how to add an option with an associated activity flag, enabling conditional application of settings. It includes adding a string option 'myOption' and a boolean flag 'myOption' in PlatformToggles. The ApplySettings, SelectPlatform, and DeletePlatform attributes are demonstrated for managing option behavior during platform operations. ```csharp namespace YG.Insides { public partial class ProjectSettings // Или CommonOptions { public string myOption; // Добавление опции [ApplySettings] public void MyApplySettings() { // Сработает при применении настроек платформы. Пример: // Получаем ссылку на флаги опций PlatformToggles toggles = YG2.infoYG.platformToggles; // Если флаг активный - применяем опцию if (toggles.myOption == true) myOption = "apply"; } [SelectPlatform] public void MySelectPlatform() { // Сработает при выборе платформы } [DeletePlatform] public void MyDeletePlatform() { // Сработает перед удаление платформы из проекта } } // Добавьте флаг активности public partial class PlatformToggles { public bool myOption; // Флаг должен называться также как опция } } ``` -------------------------------- ### Handle TV Remote Key Presses in C# Source: https://max-games.ru/plugin-yg/doc/tv This C# code snippet demonstrates how to subscribe to and handle TV remote key press and release events provided by PluginYG. It includes examples for directional keys and other media buttons. Ensure the YG namespace is imported. ```csharp using YG; private void OnEnable() { YG2.onTVKeyDown += OnKeyDown; YG2.onTVKeyUp += OnKeyUp; // Optional: for key up events } private void OnDisable() { YG2.onTVKeyDown -= OnKeyDown; YG2.onTVKeyUp -= OnKeyUp; // Optional: for key up events } private void OnKeyDown(string key) { sswitch(key) { case "Left": // Handle Left arrow key press break; case "Right": // Handle Right arrow key press break; case "Up": // Handle Up arrow key press break; case "Down": // Handle Down arrow key press break; case "Enter": // Handle Enter key press break; case "MediaRewind": // Handle Media Rewind key press break; case "MediaPlayPause": // Handle Media Play/Pause key press break; case "MediaFastForward": // Handle Media Fast Forward key press break; } } private void OnKeyUp(string key) { // Handle key up events if needed } ``` -------------------------------- ### Android Wi-Fi ADB Connect (ADB Build) Source: https://max-games.ru/plugin-yg/doc/other Facilitates connecting Android devices to Unity over Wi-Fi without cables, enabling faster build installations, convenient testing, and persistent connections. ```APIDOC ## Android Wi-Fi ADB Connect (ADB Build) ### Description Connect your Android device to Unity wirelessly via Wi-Fi using ADB. This feature simplifies the process of installing builds, testing applications, and maintaining a stable connection without the need for a physical USB cable. ### Benefits - **Cable-Free Connection**: Connect and test without USB cables. - **Fast Build Installation**: Streamline the process of deploying builds to your device. - **Convenient Testing**: Easily test your game or application on a physical device. - **Smart Long-Term Connection**: Maintain a stable connection for extended testing sessions. ``` -------------------------------- ### Accessing Environment Data in Unity (C#) Source: https://max-games.ru/plugin-yg/doc/envir Demonstrates how to import and use the EnvirData module to access various environment parameters like device type, language, domain, and browser information. It shows examples of retrieving device type as a string, boolean flags, and an enum. ```csharp using UnityEngine; using YG; public class MyClass : MonoBehaviour { public void MyMethod() { // deviceType может возвращать: desktop, mobile, tablet, tv string deviceStr = YG2.envir.deviceType; // Есть bool поля: isDesktop, isMobile, isTablet, isTV bool deviceIsDesktop = YG2.envir.isDesktop; // Поле enum: YG2.Device device = YG2.envir.device; // Other fields: string language = YG2.envir.language; // e.g., 'ru', 'en' string domain = YG2.envir.domain; // e.g., 'ru', 'com' string appID = YG2.envir.appID; // e.g., '177895' string browserLang = YG2.envir.browserLang; // e.g., 'ru' string payload = YG2.envir.payload; // Passed via URL string platform = YG2.envir.platform; // e.g., 'Win32' string browser = YG2.envir.browser; // e.g., 'Yandex', 'Chrome' } } ``` -------------------------------- ### Basic PluginYG Initialization and Ad Display Source: https://max-games.ru/plugin-yg/doc/index Shows how to initialize the PluginYG namespace and call a method to display interstitial ads. This is a fundamental step for integrating ad functionality into your game. ```csharp using YG; // To display interstitial ads: YG2.InterstitialAdvShow(); ``` -------------------------------- ### Асинхронная инициализация SDK (C#) Source: https://max-games.ru/plugin-yg/doc/platform/create-platform Пример асинхронной инициализации SDK при запуске игры. Используется для платформ, где SDK требует ожидания готовности перед использованием. ```csharp public void InitAwake() { if (CrazySDK.IsAvailable) // Требования CrazyGames { CrazySDK.Init(() => { YG2.SyncInitialization(); }); } } ``` -------------------------------- ### Реализация вызова метода SDK (C#) Source: https://max-games.ru/plugin-yg/doc/platform/create-platform Пример реализации метода игровой платформы для вызова соответствующего метода SDK. Показывает, как делегировать игровые события SDK. ```csharp public void GameplayStart() { CrazySDK.Game.GameplayStart(); } ``` -------------------------------- ### Update GamePix Level Source: https://max-games.ru/plugin-yg/doc/gamepix Call this function whenever the user advances to a new level. It accepts only numerical values representing the level. This method is specific to the GamePix platform integration. ```csharp #if GamePixPlatform_yg YG2.optionalPlatform.UpdateGamePixLevel(2); #endif ``` -------------------------------- ### Сокращенная реализация вызова метода SDK (C#) Source: https://max-games.ru/plugin-yg/doc/platform/create-platform Краткая версия реализации метода игровой платформы для вызова соответствующего метода SDK с использованием стрелочной функции. ```csharp public void GameplayStart() => CrazySDK.Game.GameplayStart(); ``` -------------------------------- ### Update GamePix Score Source: https://max-games.ru/plugin-yg/doc/gamepix Call this function each time the player's score is updated in the game. It accepts only numerical values representing the score. This method is specific to the GamePix platform integration. ```csharp #if GamePixPlatform_yg YG2.optionalPlatform.UpdateGamePixScore(100); #endif ``` -------------------------------- ### Базовая структура скрипта платформы (C#) Source: https://max-games.ru/plugin-yg/doc/platform/create-platform Базовый шаблон скрипта для реализации интерфейса IPlatformsYG2. Содержит заглушки для методов инициализации и игрового цикла. Требует настройки директивы препроцессора для активации. ```csharp #if CrazyGamesPlatform_yg namespace YG { public partial class PlatformYG2 : IPlatformsYG2 { public void InitAwake() { } public void InitStart() { } public void InitComplete() { } public void GameplayStart() { } public void GameplayStop() { } public void HappyTime() { } } } #endif ``` -------------------------------- ### Реализация метода с использованием модуля (C#) Source: https://max-games.ru/plugin-yg/doc/platform/create-platform Пример реализации метода игровой платформы, который использует функциональность отдельного модуля SDK. Требует дополнительной директивы препроцессора для модуля. ```csharp #if CrazyGamesPlatform_yg && MyMethod_yg // + && MyMethod_yg namespace YG { public partial class PlatformYG2 : IPlatformsYG2 { public void MyMethod() { // Реализация } } } #endif ``` -------------------------------- ### JavaScript Method for Game Interaction Source: https://max-games.ru/plugin-yg/doc/create-module Example of a JavaScript function within index.html that interacts with the Yandex SDK's Gameplay API. It also demonstrates how to call back into Unity using YG2Instance, which is a custom function similar to sendMessage. ```javascript function GameplayStart() { // Check if the SDK is initialized if (ysdk == null) return; ysdk.features.GameplayAPI.start(); // Example of calling a method from JS to Unity YG2Instance("MethodName", "param"); } ``` -------------------------------- ### Importing and Using PluginYG Modules Source: https://max-games.ru/plugin-yg/doc/index Demonstrates how to import a module like InterstitialAdv into your project. Imported modules are placed in the 'Modules' folder, and their global settings appear in the plugin's settings. Each module also creates a preprocessor directive (define) that can be used in your code. ```text 1. Open your version control tool. 2. Download and import the **InterstitialAdv** module. When the module is imported: 1. It is placed in the **Modules** folder. Any folder in the Modules directory will be recognized as a plugin module. 2. If the module has global settings, they will appear in the plugin settings. 3. A define (preprocessor directive) will be created for all modules. You can use this in your code. ``` -------------------------------- ### Saving Integer Stats with PlayerStats in C# Source: https://max-games.ru/plugin-yg/doc/storage Illustrates how to use the PlayerStats module for saving integer data. It demonstrates using `YG2.SetState` to save a value, `YG2.GetState` to retrieve it, and `YG2.GetAllStats` to get all saved stats. Data is saved asynchronously. ```csharp // Save an integer state YG2.SetState("saveName", integerValue); // Get an integer state int value = YG2.GetState("saveName"); // Get all saved stats Dictionary allStats = YG2.GetAllStats(); // Set all stats (can be used to clear saves) // YG2.SetAllStats(new Dictionary()); // Load stats manually if needed (asynchronous) // YG2.LoadStats(); // event onGetSDKData will be called when data is ready. ``` -------------------------------- ### Handling Game Focus and Window Events with PluginYG Source: https://max-games.ru/plugin-yg/doc/index Illustrates how to detect and react to game focus events using PluginYG. This is crucial for managing game state when the player switches between your game and other applications or tabs. ```csharp // Event triggered when the game window gains focus: // onShowWindowGame += YourFocusHandler; // Event triggered when the game window loses focus: // onHideWindowGame += YourHideHandler; // Check if the game is currently in focus: bool isInFocus = YG2.isFocusWindowGame; ``` -------------------------------- ### Safely Get and Convert Flags in Unity C# Source: https://max-games.ru/plugin-yg/doc/flags Shows how to safely retrieve flags and attempt to convert them to specific data types (string, int, float, bool) using `YG2.TryGetFlag` and its type-specific variants. This method is robust against malformed values. ```csharp if (YG2.TryGetFlag("difficult", out string difficult)) { // Флаг существует, пользуемся им! Debug.Log(difficult); } if (YG2.TryGetFlagAsInt("intType", out int intType)) { // Флаг существует и преобразован в тип int } if (YG2.TryGetFlagAsFloat("floatType", out float floatType)) { // Флаг существует и преобразован в тип float } if (YG2.TryGetFlagAsBool("boolType", out bool boolType)) { // Флаг существует и преобразован в тип bool } ``` -------------------------------- ### Asynchronous Initialization for YG Platform Modules (C#) Source: https://max-games.ru/plugin-yg/doc/platform/create-platform Handles asynchronous initialization for YG platform modules, including user data for Crazy Games. It uses CrazySDK.Init with a callback to ensure proper initialization order and calls YG2.SyncInitialization upon completion. This method should be called within InitAwake. ```csharp #if CrazyGamesPlatform_yg using CrazyGames; namespace YG { public partial class PlatformYG2 : IPlatformsYG2 { #if Authorization_yg public PortalUser User; #endif public void InitAwake() { if (CrazySDK.IsAvailable) { CrazySDK.Init(() => { #if Authorization_yg if (CrazySDK.User.IsUserAccountAvailable) { CrazySDK.User.GetUser(user => { User = user; YG2.SyncInitialization(); }); } else { YG2.SyncInitialization(); } #else YG2.SyncInitialization(); #endif }); } } } } #endif ``` -------------------------------- ### Initialize Environment Data for YG Platform (C#) Source: https://max-games.ru/plugin-yg/doc/platform/create-platform Initializes environment data such as language, browser, platform, and device type for the YG platform. It checks for user account availability and maps device types to boolean flags. This method is called by GetEnvirData. ```csharp #if CrazyGamesPlatform_yg && EnvirData_yg using CrazyGames; namespace YG { public partial class PlatformYG2 : IPlatformsYG2 { public void InitEnirData() { if (CrazySDK.User.IsUserAccountAvailable) // Требование платформы { YG2.envir.language = CrazySDK.User.SystemInfo.countryCode.ToLower(); YG2.envir.browser = CrazySDK.User.SystemInfo.browser.name; YG2.envir.platform = CrazySDK.User.SystemInfo.os.name; string device = CrazySDK.User.SystemInfo.device.type; YG2.envir.deviceType = device; switch (device) { case "desktop": YG2.envir.isDesktop = true; break; case "tablet": YG2.envir.isTablet = true; break; case "mobile": YG2.envir.isMobile = true; break; } } } public void GetEnvirData() { InitEnirData(); YG2.GetDataInvoke(); } } } #endif ``` -------------------------------- ### Fallback Server Time Implementation (C#) Source: https://max-games.ru/plugin-yg/doc/server-time This code snippet represents the standard implementation for obtaining server time on platforms that do not provide a native API. It uses `DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()` to get the current UTC time in milliseconds, ensuring consistent functionality across different environments. ```csharp DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); ``` -------------------------------- ### Get Server Time (C#) Source: https://max-games.ru/plugin-yg/doc/server-time Retrieves the current server time in milliseconds since the Unix epoch. This is crucial for implementing time-based game mechanics like daily rewards. The value is a `long` type. For Unity Editor simulation, it uses the 'Server Time' field from module settings. ```csharp long serverTimeMilliseconds = YG2.ServerTime(); ``` -------------------------------- ### Initialize YandexGame Platform Data in Unity (C#) Source: https://max-games.ru/plugin-yg/doc/create-module This C# code snippet demonstrates how to define initialization methods for the YandexGame platform within the Unity Editor. It uses preprocessor directives to ensure the code compiles only within the Unity Editor environment and utilizes helper methods to insert asynchronous JavaScript calls into the initialization sequence. ```csharp #if YandexGamesPlatform_yg namespace YG.EditorScr.BuildModify { public partial class ModifyBuild { public static void EnvirData() { InitFunction("RequestingPlayerData", CodeType.Init); await RequestingPlayerData(); LogStyledMessage('Init ИмяМодуля ysdk'); AddIndexCode("await RequestingEnvironmentData();", CodeType.Init); } } } #endif ``` -------------------------------- ### Прямое редактирование index.html и style.css Source: https://max-games.ru/plugin-yg/doc/template Этот скрипт демонстрирует прямое редактирование файлов index.html и style.css. Вы можете получить полный текст файла в переменные `indexFile` и `styleFile`, внести изменения и они будут применены автоматически. ```csharp namespace YG.EditorScr.BuildModify { public partial class ModifyBuild { string copyCode = YG2.infoYG.Templates.myCSS; styleFile += $"\n{copyCode}"; } } ``` -------------------------------- ### YandexGame Initialization Interface (C#) Source: https://max-games.ru/plugin-yg/doc/create-module This C# code defines a partial interface `IPlatformsYG2` for the YandexGame platform. It includes a placeholder method `InitPlayer` which can be implemented by specific platform integrations to handle player-specific initialization logic. ```csharp using System; using System.Runtime.InteropServices; using UnityEngine; namespace YG { public partial interface IPlatformsYG2 { void InitPlayer() { } } ``` -------------------------------- ### YandexGame SDK Initialization in index.html (JavaScript) Source: https://max-games.ru/plugin-yg/doc/create-module This JavaScript code snippet shows the structure of the `index.html` file for initializing the YandexGame SDK. It includes the main asynchronous function `InitYSDK` which handles the SDK initialization and calls other asynchronous methods for additional modules and data retrieval. ```javascript async function InitYSDK() { ysdk = await YaGames.init(); // Additional init0 modules // Additional init1 modules // Additional init2 modules // Additional init modules await RequestingEnvironmentData(); LogStyledMessage('Init ИмяМодуля ysdk'); // Завершение инициализации SDK... } ``` -------------------------------- ### Вставка JS кода в index.html Source: https://max-games.ru/plugin-yg/doc/template Этот скрипт позволяет вставлять JavaScript код в файл index.html вашего YandexGames шаблона. Вы можете копировать код из файлов, заменять значения и выбирать тип вставки (JS, Head, Body, Init). ```csharp #if YandexGamesPlatform_yg namespace YG.EditorScr.BuildModify { public partial class ModifyBuild { public static void MyMethod() { if (YG2.infoYG.Templates.myParam) { string copyCode = FileTextCopy("Scripts/Editor/MyCopyFile.js"); copyCode = copyCode.Replace("___TEXT_REPLACE___", YG2.infoYG.Templates.myReplaceText); AddIndexCode(copyCode, CodeType.JS); } } } } #endif ```