### Initialize Yandex SDK and Start Unity Instance Source: https://github.com/justplay-max/unity-pluginyg-2/blob/main/Assets/WebGLTemplates/YandexGames/index.html Initializes the Yandex SDK and starts the Unity instance if not already loaded. Handles local host checks and synchronous initialization. ```javascript progressBarEmpty.style.display = ""; const adjustedProgress = Math.max(progress, 0.05); progressBarFull.style.width = `${100 * adjustedProgress}% `; }).then((unityInstance) => { ygGameInstance = unityInstance; loadingCover.style.background = ""; loadingCover.style.display = "none"; FocusGame(); // Fill Background [Build Modify] }).catch((message) => { console.error(message); }); }; InstallBlurFocusBlocker(); InitYSDK(); if (IsLocalHost() || syncInit) StartUnityInstance_IfUnloaded(); }; ``` -------------------------------- ### Install Blur Focus Blocker Source: https://github.com/justplay-max/unity-pluginyg-2/blob/main/Assets/WebGLTemplates/YandexGames/index.html Installs a listener to create a fixed, transparent button overlay when the window loses focus, preventing accidental interaction with the document body until focus is regained. ```javascript function InstallBlurFocusBlocker() { if (!('onblur' in document)) return; if (window.blurFocusHandlersInstalled) return; window.addEventListener('blur', function () { let blockerButton = document.createElement('button'); blockerButton.style.position = 'fixed'; blockerButton.style.top = '0'; blockerButton.style.left = '0'; blockerButton.style.width = '100%'; blockerButton.style.height = '100%'; blockerButton.style.zIndex = '9999'; blockerButton.style.backgroundColor = 'rgba(0, 0, 0, 0)'; blockerButton.style.border = 'none'; blockerButton.style.cursor = 'default'; document.body.appendChild(blockerButton); function removeBlocker() { if (blockerButton && blockerButton.parentNode) { blockerButton.parentNode.removeChild(blockerButton); } window.removeEventListener('focus', removeBlocker); } window.addEventListener('focus', removeBlocker); }); window.blurFocusHandlersInstalled = true; } ``` -------------------------------- ### Start Unity Instance if Unloaded Source: https://github.com/justplay-max/unity-pluginyg-2/blob/main/Assets/WebGLTemplates/YandexGames/index.html Checks if the loading spinner is still displayed and starts the Unity instance if it is. ```javascript function StartUnityInstance_IfUnloaded() { if (spinner.style.display !== "none") StartUnityInstance(); } ``` -------------------------------- ### Load Unity Instance Script Source: https://github.com/justplay-max/unity-pluginyg-2/blob/main/Assets/WebGLTemplates/YandexGames/index.html Dynamically creates and appends a script tag to load the Unity game's loader script. The `onload` event handler is set to start the Unity instance creation process. ```javascript const script = document.createElement("script"); script.src = loaderUrl; script.onload = () => { StartUnityInstance = function () { createUnityInstance(canvas, config, (progress) => { spinner.style.display = "none"; ``` -------------------------------- ### Initialize Yandex SDK Source: https://github.com/justplay-max/unity-pluginyg-2/blob/main/Assets/WebGLTemplates/YandexGames/index.html Asynchronously initializes the Yandex Games SDK, sets up event listeners for pause and resume, and logs success or errors. ```javascript async function InitYSDK() { try { if (IsLocalHost()) return; ysdk = await YaGames.init(); ysdk.on('game_api_pause', PauseCallback); ysdk.on('game_api_resume', ResumeCallback); // Additional init0 modules // Additional init1 modules // Additional init2 modules // Additional init modules initYSDK = true; if (ygGameInstance != null) ygGameInstance.SendMessage('YG2Instance', 'InitSDKComplete'); LogStyledMessage('Init YandexSDK Success'); } catch (e) { console.error('CRASH Initialization SDK: ', e); } if (!IsLocalHost() && !syncInit) StartUnityInstance_IfUnloaded(); } ``` -------------------------------- ### Initialize Game Logic Source: https://github.com/justplay-max/unity-pluginyg-2/blob/main/Assets/WebGLTemplates/YandexGames/index.html Sets the game initialization flag and ensures the game is paused if it was already in a paused state. ```javascript function InitGame() { initGame = true; setTimeout(function () { if (isPausedGame == true) YG2Instance('SetPauseGame', 'true'); }, 100); // Additional start modules } ``` -------------------------------- ### Background Image Configuration Source: https://github.com/justplay-max/unity-pluginyg-2/blob/main/Assets/WebGLTemplates/YandexGames/index.html Conditionally sets the background image for the loading screen based on project settings. The image is applied with a cover display mode. ```javascript #if BACKGROUND_FILENAME var backgroundUnity = "url('" + buildUrl + "/{{{ BACKGROUND_FILENAME.replace(/'/g, '%27') }}}\') center / cover"; #endif loadingCover.style.background = "url('Images/background.png') center / cover"; ``` -------------------------------- ### Yandex Games Unity Configuration Source: https://github.com/justplay-max/unity-pluginyg-2/blob/main/Assets/WebGLTemplates/YandexGames/index.html Defines the configuration object for initializing the Unity instance. This includes URLs for data, framework, code, and optional memory/symbols files, along with company and product details. ```javascript const hideFullScreenButton = ""; const buildUrl = "Build"; const loaderUrl = buildUrl + "/{{{ LOADER_FILENAME }}}"; const config = { dataUrl: buildUrl + "/{{{ DATA_FILENAME }}}", frameworkUrl: buildUrl + "/{{{ FRAMEWORK_FILENAME }}}", codeUrl: buildUrl + "/{{{ CODE_FILENAME }}}", #if MEMORY_FILENAME memoryUrl: buildUrl + "/{{{ MEMORY_FILENAME }}}", #endif #if SYMBOLS_FILENAME symbolsUrl: buildUrl + "/{{{ SYMBOLS_FILENAME }}}", #endif streamingAssetsUrl: "StreamingAssets", companyName: "{{{ COMPANY_NAME }}}", productName: "{{{ PRODUCT_NAME }}}", productVersion: "{{{ PRODUCT_VERSION }}}" }; ``` -------------------------------- ### Send Message to YG2Instance (No Argument) Source: https://github.com/justplay-max/unity-pluginyg-2/blob/main/Assets/WebGLTemplates/YandexGames/index.html Sends a message to the 'YG2Instance' in Unity. If the game is not initialized, it queues the message for later execution. ```javascript function YG2Instance(method) { if (ygGameInstance == null) return; if (!initGame) { setTimeout(function () { if (ygGameInstance) ygGameInstance.SendMessage('YG2Instance', method); }, 100); } else { ygGameInstance.SendMessage('YG2Instance', method); } } ``` -------------------------------- ### Event Listeners for Game Interaction Source: https://github.com/justplay-max/unity-pluginyg-2/blob/main/Assets/WebGLTemplates/YandexGames/index.html Sets up event listeners for various browser and Yandex SDK events to manage game focus, visibility, and interaction. ```javascript document.addEventListener('contextmenu', event => event.preventDefault()); document.addEventListener('visibilitychange', () => SetVisibility(!document.hidden)); window.addEventListener('blur', () => SetVisibility(false)); window.addEventListener('focus', () => SetVisibility(true)); window.addEventListener('pointerdown', () => { FocusGame(); SetVisibility(true); }); window.addEventListener('resize', () => FocusGame()); document.addEventListener('fullscreenchange', () => FocusGame()); ``` -------------------------------- ### Send Message to YG2Instance (With Argument) Source: https://github.com/justplay-max/unity-pluginyg-2/blob/main/Assets/WebGLTemplates/YandexGames/index.html Sends a message with an argument to the 'YG2Instance' in Unity. Queues the message if the game is not yet initialized. ```javascript function YG2Instance(method, arg) { if (ygGameInstance == null) return; if (!initGame) { setTimeout(function () { ygGameInstance.SendMessage('YG2Instance', method, arg); }, 100); } else { ygGameInstance.SendMessage('YG2Instance', method, arg); } } ``` -------------------------------- ### Pause and Resume Callbacks Source: https://github.com/justplay-max/unity-pluginyg-2/blob/main/Assets/WebGLTemplates/YandexGames/index.html Defines callback functions for pausing and resuming the game, interacting with the Yandex SDK to set the game's pause state and manage focus. ```javascript const PauseCallback = () => { isPausedGame = true; YG2Instance('SetPauseGame', 'true'); }; const ResumeCallback = () => { isPausedGame = false; YG2Instance('SetPauseGame', 'false'); FocusGame(false); }; ``` -------------------------------- ### Unity Editor Script for Plugin YG Update Source: https://github.com/justplay-max/unity-pluginyg-2/blob/main/Assets/PluginYourGames/Scripts/Server/Editor/UpdatePluginYGTemp.txt This C# script runs in the Unity Editor to automate package updates. It handles downloading, importing, and cleaning up old versions of the Plugin YG. ```csharp #if UNITY_EDITOR using System.IO; using System.Net.Http; using UnityEditor; using UnityEngine; [InitializeOnLoad] public class UpdatePluginYGTemp { public static string EXAMPLE_SCENES = string.Empty; static UpdatePluginYGTemp() => InitializeOnLoad(); private static void InitializeOnLoad() { EditorApplication.delayCall += () => { ImportPackage(); }; } private static async void ImportPackage() { try { string downloadPath = $"{Application.dataPath}/PlyginYG2_tempYG.unitypackage"; using (HttpClient client = new HttpClient()) { DeletePluginYG(); HttpResponseMessage response = await client.GetAsync("DOWNLOAD_URL_KEY"); response.EnsureSuccessStatusCode(); byte[] packageBytes = await response.Content.ReadAsByteArrayAsync(); File.WriteAllBytes(downloadPath, packageBytes); AssetDatabase.ImportPackage(downloadPath, false); File.Delete(downloadPath); } } catch (System.Exception ex) { Debug.LogError(ex); } finally { if (EXAMPLE_SCENES != string.Empty) { string directory = $"{Application.dataPath}/PATH_YG2/Example/Resources"; Directory.CreateDirectory(directory); File.WriteAllText($"{directory}/DemoSceneNames.txt", EXAMPLE_SCENES); } File.Delete($"{Application.dataPath}/UpdatePluginYGTemp.cs"); } } public static void DeletePluginYG() { SessionState.SetBool("PluginYG_LoadServerComplete", false); string startPath = $"{Application.dataPath}/PATH_YG2"; DeleteDirectory($"{startPath}/Example"); DeleteDirectory($"{startPath}/Scripts"); AssetDatabase.Refresh(); } public static void DeleteDirectory(string folderDelete) { if (!Directory.Exists(folderDelete)) return; FileUtil.DeleteFileOrDirectory(folderDelete); FileUtil.DeleteFileOrDirectory(folderDelete + ".meta"); } } #endif ``` -------------------------------- ### Check if Running on Local Host Source: https://github.com/justplay-max/unity-pluginyg-2/blob/main/Assets/WebGLTemplates/YandexGames/index.html Determines if the current environment is a local development server. Avoids Yandex SDK initialization on local hosts. ```javascript function IsLocalHost() { try { if (window.top !== window) { return false; } const host = window.location.hostname; if (host === "localhost" || host === "127.0.0.1" || host.endsWith(".local")) { LogStyledMessage("Local Host"); return true; } } catch (error) { console.error("Error checking the local host:", error); return false; } } ``` -------------------------------- ### Mobile Device Detection and Styling Source: https://github.com/justplay-max/unity-pluginyg-2/blob/main/Assets/WebGLTemplates/YandexGames/index.html Adjusts the container class for mobile devices based on user agent detection. This is typically used to apply specific mobile styling or configurations. ```javascript if (/iPhone|iPad|iPod|Android/i.test(navigator.userAgent)) { container.className = "unity-mobile"; //config.devicePixelRatio = 1; } ``` -------------------------------- ### Log Styled Message Source: https://github.com/justplay-max/unity-pluginyg-2/blob/main/Assets/WebGLTemplates/YandexGames/index.html Logs a message to the console with custom styling. Useful for highlighting important information during development. ```javascript function LogStyledMessage(message, style = 'color: #FFDF73; background-color: #454545') { console.log('%c' + message, style); } ``` -------------------------------- ### Custom Pointer Lock Implementation Source: https://github.com/justplay-max/unity-pluginyg-2/blob/main/Assets/WebGLTemplates/YandexGames/index.html Overrides the native `requestPointerLock` method to include an `unadjustedMovement` option, potentially for smoother input handling in games. ```javascript const oRequestPointerLock = Element.prototype.requestPointerLock; Element.prototype.requestPointerLock = async function hkRequestPointerLock(...args) { try { (args[0] ||= {}).unadjustedMovement = true; await oRequestPointerLock.apply(this, args); } catch (err) { console.log(err); } }; ``` -------------------------------- ### Set Visibility Function for Yandex SDK Source: https://github.com/justplay-max/unity-pluginyg-2/blob/main/Assets/WebGLTemplates/YandexGames/index.html Updates the game's focus status with the Yandex SDK based on window visibility changes. This function is called when the document's visibility changes or when the window gains/loses focus. ```javascript function SetVisibility(visibility) { if (ysdk !== null && initGame === true && isVisibility !== visibility) { isVisibility = visibility; if (!visibility) { YG2Instance('SetFocusWindowGame', 'false'); } else { YG2Instance('SetFocusWindowGame', 'true'); } } } ``` -------------------------------- ### Focus Game Function Source: https://github.com/justplay-max/unity-pluginyg-2/blob/main/Assets/WebGLTemplates/YandexGames/index.html Manages focusing the Unity canvas, ensuring it receives input events. It includes logic to prevent focus if the game is paused or if an input element is active. ```javascript function FocusGame(checkingPauseStatus = true) { if (!canvas) return; requestAnimationFrame(() => { if (checkingPauseStatus && isPausedGame) return; const active = document.activeElement; if (active && (active.tagName === 'INPUT' || active.tagName === 'TEXTAREA' || active.isContentEditable )) { return; } canvas.focus({ preventScroll: true }); }); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.