### Install Package from Git URL Source: https://github.com/wanted5games/unity-game-interface-package/blob/main/README.md Instructions for installing the package using Unity's Package Manager by providing a Git URL. ```bash https://github.com/wanted5games/unity-game-interface-package.git ``` -------------------------------- ### Handle Game Lifecycle Events with Async/Await Source: https://context7.com/wanted5games/unity-game-interface-package/llms.txt Demonstrates starting a level with an interstitial ad and awaiting GameStart using the async/await pattern. ```csharp public class LevelManager : MonoBehaviour { // async/await pattern public async void StartLevel(int level) { // Show interstitial before game start, then await GameStart await GameInterface.Instance.ShowInterstitialAd("button:menu:start", "start"); await GameInterface.Instance.GameStart(level); // Level gameplay begins here } // GameOver on failure public async void FailLevel() { await GameInterface.Instance.GameOver(); // Show result/retry screen after promise resolves } // Pause/Resume during gameplay public async void PauseGame() { await GameInterface.Instance.GamePause(); Time.timeScale = 0f; } public async void ResumeGame() { await GameInterface.Instance.GameResume(); Time.timeScale = 1f; } } ``` -------------------------------- ### Sample Scene and Script Source: https://github.com/wanted5games/unity-game-interface-package/blob/main/README.md Explore the included sample scene and example script to quickly test and understand the Game Interface features. Remember to copy the sample scene to your Assets folder before opening. ```APIDOC ## Samples A sample scene is included to help you quickly test and understand the Game Interface features. - **Scene:** `Packages/Game Interface/Samples/Scenes/SampleScene.scene` - **Example Script:** `Packages/Game Interface/Samples/Scripts/GameInterfaceExample.cs` ⚠️ **Important**: To open the sample scene, you must copy it to your `Assets/` folder first. Scenes located in the `Packages/` folder cannot be opened directly in Unity. These demonstrate how to use the Game Interface API and test event hooks during gameplay. ``` -------------------------------- ### Install Unity Game Interface Package from Git Source: https://context7.com/wanted5games/unity-game-interface-package/llms.txt Instructions for adding the package to your Unity project using the Package Manager. ```bash // Window > Package Manager > + > Add package from git URL: https://github.com/wanted5games/unity-game-interface-package.git ``` -------------------------------- ### Storage System: Set, Get, Remove, Clear Source: https://context7.com/wanted5games/unity-game-interface-package/llms.txt Manages game data using a platform-aware storage system with caching and size monitoring. Supports primitives and JSON-serializable objects. Configure storage limits in Awake. ```csharp [System.Serializable] public class PlayerSaveData { public string playerName = ""; public int highScore = 0; public float volume = 1.0f; } public class SaveSystem : MonoBehaviour { // Configurable limits private void Awake() { GameInterface.Instance.MaxStorageItemBytes = 512 * 1024; // 512 KB per item GameInterface.Instance.MaxTotalStorageBytes = 2 * 1024 * 1024; // 2 MB total } public void Save(PlayerSaveData data) { GameInterface.Instance.SetStorageItem("playerName", data.playerName); GameInterface.Instance.SetStorageItem("highScore", data.highScore); GameInterface.Instance.SetStorageItem("volume", data.volume); GameInterface.Instance.SetStorageItem("saveData", data); // serialized as JSON } public PlayerSaveData Load() { // Typed getters — uses cache if available string name = GameInterface.Instance.GetStorageItem("playerName"); int score = GameInterface.Instance.GetStorageItem("highScore"); float volume = GameInterface.Instance.GetStorageItem("volume"); // Or load the entire object PlayerSaveData full = GameInterface.Instance.GetStorageItem("saveData"); return full; } public void ResetSave() { GameInterface.Instance.RemoveItem("highScore"); // Or wipe everything: GameInterface.Instance.ClearStorage(); } } ``` -------------------------------- ### Game Lifecycle Methods Source: https://context7.com/wanted5games/unity-game-interface-package/llms.txt Methods to manage the game's lifecycle, including starting, completing, ending, quitting, pausing, and resuming the game. ```APIDOC ## Game Lifecycle — GameStart / GameComplete / GameOver / GameQuit / GamePause / GameResume These methods wrap the JS GameInterface lifecycle. Each returns a `Task` that must resolve before advancing game state. `GameStart` accepts an optional level number. ```csharp public class LevelManager : MonoBehaviour { // async/await pattern public async void StartLevel(int level) { // Show interstitial before game start, then await GameStart await GameInterface.Instance.ShowInterstitialAd("button:menu:start", "start"); await GameInterface.Instance.GameStart(level); // Level gameplay begins here } // Callback pattern public void CompleteLevel() { GameInterface.Instance.GameComplete( onComplete: () => Debug.Log("GameComplete resolved — show result screen"), onError: err => Debug.LogError($"GameComplete failed: {err}") ); } // GameOver on failure public async void FailLevel() { await GameInterface.Instance.GameOver(); // Show result/retry screen after promise resolves } // Coroutine pattern for GameQuit public void QuitToMenu() => StartCoroutine(QuitCoroutine()); private IEnumerator QuitCoroutine() { var task = GameInterface.Instance.GameQuit(); yield return TaskExtensions.WaitForTask(task); // Safe to navigate away now UnityEngine.SceneManagement.SceneManager.LoadScene("MainMenu"); } // Pause/Resume during gameplay public async void PauseGame() { await GameInterface.Instance.GamePause(); Time.timeScale = 0f; } public async void ResumeGame() { await GameInterface.Instance.GameResume(); Time.timeScale = 1f; } } ``` ``` -------------------------------- ### Initialize Game Interface and Signal Readiness Source: https://context7.com/wanted5games/unity-game-interface-package/llms.txt Shows how to report loading progress, mute state, disable the splash screen, and signal game readiness using async/await. ```csharp public class MyGameLoader : MonoBehaviour { private async void Awake() { // Report loading progress as assets load GameInterface.Instance.SendPreloadProgress(0); await LoadAssetsAsync(progress => GameInterface.Instance.SendPreloadProgress(progress)); // Report player-controlled mute state before GameReady GameInterface.Instance.GameMuted(false); // Hide splash screen and signal game is ready GameInterface.Instance.DisableSplashScreen(); GameInterface.Instance.GameReady(); // Start listening for visibility changes GameInterface.Instance.InitVisibilityChange(); } private async System.Threading.Tasks.Task LoadAssetsAsync(System.Action onProgress) { for (int i = 0; i <= 100; i += 10) { await System.Threading.Tasks.Task.Delay(50); onProgress(i); } } } ``` -------------------------------- ### Initialization Methods Source: https://context7.com/wanted5games/unity-game-interface-package/llms.txt Methods for reporting preload progress, signaling game readiness, and disabling the splash screen. ```APIDOC ## Initialization — SendPreloadProgress / GameReady / DisableSplashScreen `SendPreloadProgress(int progress)` reports loading progress (0–100) during preload. `GameReady()` signals that the game is ready for play. `DisableSplashScreen()` hides the custom HTML splash screen once the game has loaded. ```csharp public class MyGameLoader : MonoBehaviour { private async void Awake() { // Report loading progress as assets load GameInterface.Instance.SendPreloadProgress(0); await LoadAssetsAsync(progress => GameInterface.Instance.SendPreloadProgress(progress)); // Report player-controlled mute state before GameReady GameInterface.Instance.GameMuted(false); // Hide splash screen and signal game is ready GameInterface.Instance.DisableSplashScreen(); GameInterface.Instance.GameReady(); // Start listening for visibility changes GameInterface.Instance.InitVisibilityChange(); } private async System.Threading.Tasks.Task LoadAssetsAsync(System.Action onProgress) { for (int i = 0; i <= 100; i += 10) { await System.Threading.Tasks.Task.Delay(50); onProgress(i); } } } ``` ``` -------------------------------- ### Initialize Game Interface Source: https://github.com/wanted5games/unity-game-interface-package/blob/main/README.md Call GameReady() on the GameInterface singleton to signal that the game is ready. ```csharp GameInterface.Instance.GameReady(); ``` -------------------------------- ### Initialize Unity Game Instance Source: https://github.com/wanted5games/unity-game-interface-package/blob/main/WebGLTemplates/GameInterface/index.html Initializes the Unity game instance with specified configuration. Use this for setting up the game's core parameters and loading assets. ```javascript window.GameInterface.init(["Build/{{{ LOADER_FILENAME }}}"], { "features": {"rewarded": true, "copyright": true, "credits": false, "visibilitychange": true }}).then(() => { document.body.style.textAlign = "left"; var canvas = document.querySelector("#unity-canvas"); var config = { dataUrl: "Build/{{{ DATA_FILENAME }}}", frameworkUrl: "Build/{{{ FRAMEWORK_FILENAME }}}", #if USE_THREADS workerUrl: "Build/{{{ WORKER_FILENAME }}}", #endif #if USE_WASM codeUrl: "Build/{{{ CODE_FILENAME }}}", #endif #if MEMORY_FILENAME memoryUrl: "Build/{{{ MEMORY_FILENAME }}}", #endif #if SYMBOLS_FILENAME symbolsUrl: "Build/{{{ SYMBOLS_FILENAME }}}", #endif streamingAssetsUrl: "StreamingAssets", companyName: {{{ JSON.stringify(COMPANY_NAME) }}}, productName: {{{ JSON.stringify(PRODUCT_NAME) }}}, productVersion: {{{ JSON.stringify(PRODUCT_VERSION) }}}, // matchWebGLToCanvasSize: false, // Uncomment this to separately control WebGL canvas render size and DOM element size. devicePixelRatio: window.devicePixelRatio, }; var savedProgress = 0; const bar = document.getElementById("progress-bar"); const percentage = document.getElementById("percentage"); createUnityInstance(canvas, config, (progress) => { progress = Math.round(progress * 100); if(progress > savedProgress) { savedProgress = progress window.GameInterface.sendPreloadProgress(progress); bar.style.width = progress + "%" percentage.innerHTML = progress + "%" } }); }); ``` -------------------------------- ### Handle Game Lifecycle Events with Callbacks Source: https://context7.com/wanted5games/unity-game-interface-package/llms.txt Shows how to complete a level using the callback pattern, providing success and error handlers. ```csharp // Callback pattern public void CompleteLevel() { GameInterface.Instance.GameComplete( onComplete: () => Debug.Log("GameComplete resolved — show result screen"), onError: err => Debug.LogError($"GameComplete failed: {err}") ); } ``` -------------------------------- ### Access GameInterface Singleton Instance Source: https://context7.com/wanted5games/unity-game-interface-package/llms.txt Demonstrates how to access the thread-safe singleton instance of the GameInterface. ```csharp // Access from anywhere in your game code var gi = GameInterface.Instance; // Equivalent static helper var gi2 = GameInterface.GetInstance(); ``` -------------------------------- ### Handle Game Lifecycle Events with Coroutines Source: https://context7.com/wanted5games/unity-game-interface-package/llms.txt Demonstrates quitting the game using a coroutine and `TaskExtensions.WaitForTask` to ensure the operation completes before scene change. ```csharp // Coroutine pattern for GameQuit public void QuitToMenu() => StartCoroutine(QuitCoroutine()); private IEnumerator QuitCoroutine() { var task = GameInterface.Instance.GameQuit(); yield return TaskExtensions.WaitForTask(task); // Safe to navigate away now UnityEngine.SceneManagement.SceneManager.LoadScene("MainMenu"); } ``` -------------------------------- ### Manage In-App Purchases with IAPManager Source: https://context7.com/wanted5games/unity-game-interface-package/llms.txt Handles product fetching, purchasing, and consumption. Requires the 'iap' feature flag. Products must be defined in famobi.json. ```csharp public class IAPManager : MonoBehaviour { private IAPProduct[] _products = new IAPProduct[0]; private void OnEnable() { GameInterface.Instance.OnIAPEvent += HandleIAPEvent; } private void OnDisable() { GameInterface.Instance.OnIAPEvent -= HandleIAPEvent; } private void Start() { if (!GameInterface.Instance.HasFeature("iap")) return; GameInterface.Instance.GetProducts( onComplete: products => { _products = products; foreach (var p in products) Debug.Log($ ``` -------------------------------- ### Additional Features Source: https://github.com/wanted5games/unity-game-interface-package/blob/main/README.md Utilize new methods in the GameInterface API for enhanced control, including disabling the splash screen, initializing visibility change listeners, and resizing the game canvas. ```APIDOC ### Additional Features The following new methods have been added to the `GameInterface` API to improve flexibility and control over runtime behavior: ```C# // Disable the custom splash screen. GameInterface.Instance.DisableSplashScreen(); // Initialize an event listener for visibility changes (if supported by the platform). GameInterface.Instance.InitVisibilityChange(); // Resize the game canvas, applying the offset for the banner. GameInterface.Instance.ResizeGameCanvas(); ``` ``` -------------------------------- ### Event Handling Source: https://github.com/wanted5games/unity-game-interface-package/blob/main/README.md Subscribe and unsubscribe from game events like OnGoToNextLevel and OnRewardedAdAvailabilityChange to react to game state changes. Remember to always unsubscribe in OnDisable to prevent memory leaks. ```APIDOC ## Event Handling You can listen for Game Interface events (e.g., OnGoToNextLevel) by subscribing to them. ```C# public void OnEnable() { GameInterface.Instance.OnGoToNextLevel += HandleGoToNextLevel; GameInterface.Instance.OnRewardedAdAvailabilityChange += HandleRewardedAdAvailabilityChange; } public void OnDisable() { GameInterface.Instance.OnGoToNextLevel -= HandleGoToNextLevel; GameInterface.Instance.OnRewardedAdAvailabilityChange -= HandleRewardedAdAvailabilityChange; } ``` ⚠️ Always unsubscribe from events in OnDisable to prevent memory leaks. ``` -------------------------------- ### Subscribe to Game Interface Events Source: https://github.com/wanted5games/unity-game-interface-package/blob/main/README.md Listen for game interface events like OnGoToNextLevel and OnRewardedAdAvailabilityChange by subscribing to them. Remember to unsubscribe in OnDisable to prevent memory leaks. ```C# public void OnEnable() { GameInterface.Instance.OnGoToNextLevel += HandleGoToNextLevel; GameInterface.Instance.OnRewardedAdAvailabilityChange += HandleRewardedAdAvailabilityChange; } public void OnDisable() { GameInterface.Instance.OnGoToNextLevel -= HandleGoToNextLevel; GameInterface.Instance.OnRewardedAdAvailabilityChange -= HandleRewardedAdAvailabilityChange; } ``` -------------------------------- ### Show Rewarded Ad with Async/Await Source: https://github.com/wanted5games/unity-game-interface-package/blob/main/README.md Displays a rewarded ad using async/await for asynchronous operations. Errors are handled with a try-catch block. Requires Unity 2017.2+ for async/await support. ```csharp public async void ShowRewardedAd() { try { var result = await GameInterface.Instance.ShowRewardedAd("test_event"); if (result.isRewardGranted) { // Reward the player. } } catch (Exception e) { Debug.LogError($"Ad failed to show: {e.Message}"); // Handle error } } ``` -------------------------------- ### Show Rewarded Ad with Coroutine Source: https://github.com/wanted5games/unity-game-interface-package/blob/main/README.md Displays a rewarded ad and waits for its completion using a coroutine. The TaskExtensions.WaitForTask method is used to convert Tasks to Coroutines. Error handling is done by checking task.IsFaulted. ```csharp using System.Collections; private IEnumerator ShowRewardedAdCoroutine() { Task task = GameInterface.Instance.ShowRewardedAd("test_event"); yield return TaskExtensions.WaitForTask(task); if (task.IsFaulted) { Debug.LogError($"Ad failed to show: {task.Exception?.GetBaseException().Message}"); // Handle error yield break; } var result = task.Result; if (result.isRewardGranted) { // Reward the player. } } ``` -------------------------------- ### Storage System Source: https://github.com/wanted5games/unity-game-interface-package/blob/main/README.md Use the GameInterface storage system as a replacement for Unity's PlayerPrefs. It offers automatic caching, size monitoring, and configurable limits for storing game data. ```APIDOC ### Storage The `GameInterface` storage system replaces Unity's `PlayerPrefs` and provides: - **Automatic caching**: Storage reads are cached in memory to reduce overhead - **Size monitoring**: Warnings are logged when individual items or total storage size approach limits (default: 1 MB each) - **Configurable limits**: Adjust `GameInterface.Instance.MaxStorageItemBytes` and `MaxTotalStorageBytes` if needed ```C# // Store data (automatically cached) GameInterface.Instance.SetStorageItem("playerName", "Player1"); GameInterface.Instance.SetStorageItem("highScore", 1000); // Retrieve data (uses cache if available) string name = GameInterface.Instance.GetStorageItem("playerName"); int score = GameInterface.Instance.GetStorageItem("highScore"); // Clear storage GameInterface.Instance.ClearStorage(); ``` ``` -------------------------------- ### Singleton Access Source: https://context7.com/wanted5games/unity-game-interface-package/llms.txt Access the `GameInterface.Instance` singleton to interact with the game interface API. It is lazily initialized and persists across scene loads. ```APIDOC ## Singleton Access `GameInterface.Instance` is the single entry point for all API calls. It is lazily initialized and persists across scene loads via a `DontDestroyOnLoad` `GameObject`. ```csharp // Access from anywhere in your game code var gi = GameInterface.Instance; // Equivalent static helper var gi2 = GameInterface.GetInstance(); ``` ``` -------------------------------- ### Manage Application Visibility with VisibilityHandler Source: https://context7.com/wanted5games/unity-game-interface-package/llms.txt Initializes the JS visibility listener and handles game pausing/unpausing based on browser tab visibility. ```csharp public class VisibilityHandler : MonoBehaviour { private void Awake() { GameInterface.Instance.InitVisibilityChange(); } private void OnEnable() { GameInterface.Instance.OnVisibilityChange += HandleVisibility; } private void OnDisable() { GameInterface.Instance.OnVisibilityChange -= HandleVisibility; } private void HandleVisibility(bool isHidden) { if (isHidden) { Time.timeScale = 0f; // Pause game when tab hidden AudioListener.pause = true; } else { if (!GameInterface.Instance.IsPaused()) { Time.timeScale = 1f; AudioListener.pause = false; } } } } ``` -------------------------------- ### Configure Ads and IAPs in famobi.json Source: https://context7.com/wanted5games/unity-game-interface-package/llms.txt Declare all ad event IDs and IAP products in this JSON file. Edit it via the Famobi.json Editor window or directly. ```json { "interstitial": { "eventIds": ["button:menu:start", "break:result"], "allowlist": ["*"], "blocklist": [] }, "rewarded": { "eventIds": ["button:gameplay:extra-life", "button:result:double-coins"], "allowlist": ["*"], "blocklist": [] }, "iap": { "products": [ { "sku": "REMOVE_ADS", "title": "Ad-Free Gaming", "description": "Remove all interstitial and rewarded ads.", "imageURI": "https://cdn.example.com/no_ads.png", "priceValue": 2.99 }, { "sku": "COIN_PACK_500", "title": "500 Coins", "description": "A pack of 500 in-game coins.", "imageURI": "https://cdn.example.com/coins.png", "priceValue": 0.99 } ] }, "schemaVersion": 1 } ``` -------------------------------- ### Handle Game Navigation Events in Unity Source: https://context7.com/wanted5games/unity-game-interface-package/llms.txt Subscribes to various game navigation events from the Game Interface, such as going home, to the next level, or quitting. Responds by performing necessary game actions and scene loading. ```csharp public class NavigationHandler : MonoBehaviour { private void OnEnable() { GameInterface.Instance.OnGoToHome += HandleGoToHome; GameInterface.Instance.OnGoToNextLevel += HandleGoToNextLevel; GameInterface.Instance.OnGoToLevel += HandleGoToLevel; GameInterface.Instance.OnRestartGame += HandleRestartGame; GameInterface.Instance.OnQuitGame += HandleQuitGame; GameInterface.Instance.OnGameOver += HandleGameOver; } private void OnDisable() { GameInterface.Instance.OnGoToHome -= HandleGoToHome; GameInterface.Instance.OnGoToNextLevel -= HandleGoToNextLevel; GameInterface.Instance.OnGoToLevel -= HandleGoToLevel; GameInterface.Instance.OnRestartGame -= HandleRestartGame; GameInterface.Instance.OnQuitGame -= HandleQuitGame; GameInterface.Instance.OnGameOver -= HandleGameOver; } private async void HandleGoToHome() { await GameInterface.Instance.GameQuit(); UnityEngine.SceneManagement.SceneManager.LoadScene("MainMenu"); } private async void HandleGoToNextLevel() { await GameInterface.Instance.GameQuit(); LoadNextLevel(); } private async void HandleGoToLevel(int level) { await GameInterface.Instance.GameQuit(); LoadLevel(level); } private async void HandleRestartGame() { await GameInterface.Instance.GameQuit(); await GameInterface.Instance.GameStart(currentLevel); } private async void HandleQuitGame() { await GameInterface.Instance.GameQuit(); Application.Quit(); } private async void HandleGameOver() { await GameInterface.Instance.GameOver(); } private int currentLevel = 1; private void LoadNextLevel() { /* scene loading logic */ } private void LoadLevel(int l) { /* scene loading logic */ } } ``` -------------------------------- ### Load Splash Screen Synchronously Source: https://github.com/wanted5games/unity-game-interface-package/blob/main/WebGLTemplates/GameInterface/index.html Loads and inserts the splash screen HTML content into the page. This is useful for displaying a loading screen before the main game content is ready. ```javascript function() { try { var xhr = new XMLHttpRequest(); xhr.open("GET", "splash.html", false); xhr.send(null); if (xhr.status === 200 || xhr.status === 0) { var backgroundDiv = document.getElementById("background"); var tempDiv = document.createElement("div"); tempDiv.innerHTML = xhr.responseText; var splashElement = tempDiv.querySelector("#application-splash"); if (splashElement && backgroundDiv) { backgroundDiv.parentNode.insertBefore(splashElement, backgroundDiv.nextSibling); } } } catch(e) { console.error("Error loading splash screen:", e); } }() ``` -------------------------------- ### Report Player Progress and Score Source: https://context7.com/wanted5games/unity-game-interface-package/llms.txt Use SendProgress to report player progress as a percentage and SendScore to report the current score. Both methods are fire-and-forget. ```csharp public class GameplayTracker : MonoBehaviour { private int _score = 0; public void AddScore(int points) { _score += points; GameInterface.Instance.SendScore(_score); } public void OnCheckpointReached(int checkpointIndex, int totalCheckpoints) { int progress = Mathf.RoundToInt((float)checkpointIndex / totalCheckpoints * 100f); GameInterface.Instance.SendProgress(progress); // e.g. 50 } } ``` -------------------------------- ### Runtime Testing Window Source: https://github.com/wanted5games/unity-game-interface-package/blob/main/README.md Utilize the Game Interface Tester window for runtime testing of various features, including event delays, ad cooldowns, and runtime states. Access it via Game Interface ▸ Tester in the Unity menu bar. ```APIDOC ## Runtime testing You can adjust settings and trigger events during gameplay to test different features of the Game Interface API. The testing window can be found under Game Interface ▸ Tester in the Unity menu bar. ![EditorWindow](Documentation/EditorWindow.png) The settings asset used by this window is located at: `Packages/Game Interface/Samples/Settings/GameInterfaceTester.asset`. If you prefer to keep this asset inside your Assets/ folder, you can create a new one via: ![MenuItem](Documentation/MenuItem.png) ⚠️ Important: Don't forget to assign your new asset to the Game Interface Tester window. ### Testing Features The Game Interface Tester window provides several testing features: - **Event Delays**: Configure delays (in milliseconds) for game events (GameStart, GameComplete, etc.), IAP events, and ad events to simulate network latency - **Interstitial Ad Cooldown**: Set a cooldown period (in milliseconds) between interstitial ad displays - **Ad Overlay**: In the Unity Editor, ads are displayed as overlays with interactive buttons: - Interstitial ads show a "Close Ad" button - Rewarded ads show "Grant Reward" and "Reject Reward" buttons for testing different reward scenarios - **Runtime State**: Adjust various runtime states like muted/paused status, rewarded ad availability, and more ``` -------------------------------- ### Handle Pause and Mute States in Unity Source: https://context7.com/wanted5games/unity-game-interface-package/llms.txt Subscribes to pause and mute state changes from the Game Interface. Applies pause by setting Time.timeScale and mute by adjusting AudioListener.volume. Reports player-initiated mute changes back to the platform. ```csharp public class AudioPauseController : MonoBehaviour { private void OnEnable() { // Check state at enable time if (GameInterface.Instance.IsPaused()) ApplyPause(true); if (GameInterface.Instance.IsMuted()) ApplyMute(true); GameInterface.Instance.OnPauseStateChange += ApplyPause; GameInterface.Instance.OnMuteStateChange += ApplyMute; } private void OnDisable() { GameInterface.Instance.OnPauseStateChange -= ApplyPause; GameInterface.Instance.OnMuteStateChange -= ApplyMute; } private void ApplyPause(bool isPaused) { Time.timeScale = isPaused ? 0f : 1f; // Show/hide pause overlay as needed (do NOT open the game's own pause menu) } private void ApplyMute(bool isMuted) { AudioListener.volume = isMuted ? 0f : 1f; } // Call this when the player taps a mute button in your UI public void OnPlayerToggleMute(bool nowMuted) { AudioListener.volume = nowMuted ? 0f : 1f; GameInterface.Instance.GameMuted(nowMuted); // Report back to platform } } ``` -------------------------------- ### Convert Task to Coroutine with TaskExtensions.WaitForTask Source: https://context7.com/wanted5games/unity-game-interface-package/llms.txt Use this to yield on asynchronous GameInterface calls within Unity coroutines. Ensure the TaskExtensions class is accessible. ```csharp public class CoroutineExample : MonoBehaviour { private void Start() { StartCoroutine(GameFlowCoroutine()); } private IEnumerator GameFlowCoroutine() { // Wait for GameStart to resolve inside a coroutine var startTask = GameInterface.Instance.GameStart(1); yield return TaskExtensions.WaitForTask(startTask); if (startTask.IsFaulted) { Debug.LogError("GameStart failed: " + startTask.Exception?.GetBaseException().Message); yield break; } Debug.Log("Game started — begin gameplay"); // … gameplay … var completeTask = GameInterface.Instance.GameComplete(); yield return TaskExtensions.WaitForTask(completeTask); Debug.Log("GameComplete resolved"); } } ``` -------------------------------- ### Game Navigation Events Source: https://context7.com/wanted5games/unity-game-interface-package/llms.txt Handles external requests for game navigation actions such as going home, to the next level, or restarting the game. ```APIDOC ## Game Navigation Events ### Description Responds to platform-initiated navigation requests. Subscribe to these events to handle actions like returning to the home screen, loading the next level, or restarting the game. ### Events - **OnGoToHome**: Triggered when the platform requests navigation to the home screen. - **OnGoToNextLevel**: Triggered when the platform requests navigation to the next level. - **OnGoToLevel(int level)**: Triggered when the platform requests navigation to a specific level. - **OnRestartGame**: Triggered when the platform requests restarting the current game. - **OnQuitGame**: Triggered when the platform requests quitting the game. - **OnGameOver**: Triggered when the game is over. ### Methods - **GameQuit()**: Asynchronously signals that the game is quitting. - **GameStart(int level)**: Asynchronously starts the game, optionally at a specific level. - **GameOver()**: Asynchronously signals that the game has ended. ### Example Usage (C#) ```csharp private void OnEnable() { GameInterface.Instance.OnGoToHome += HandleGoToHome; GameInterface.Instance.OnGoToNextLevel += HandleGoToNextLevel; // ... other event subscriptions } private async void HandleGoToHome() { await GameInterface.Instance.GameQuit(); UnityEngine.SceneManagement.SceneManager.LoadScene("MainMenu"); } private async void HandleRestartGame() { await GameInterface.Instance.GameQuit(); await GameInterface.Instance.GameStart(currentLevel); } ``` ``` -------------------------------- ### Show Rewarded Ad with Callback Source: https://github.com/wanted5games/unity-game-interface-package/blob/main/README.md Displays a rewarded ad and handles the result or errors using callback functions. Ensure the event name is correctly specified. ```csharp public void ShowRewardedAd() { GameInterface.Instance.ShowRewardedAd("test_event", (result) => { if (result.isRewardGranted) { // Reward the player. } }, (error) => { Debug.LogError($"Ad failed to show: {error}"); // Handle error (e.g., show a message to the player) }); } ``` -------------------------------- ### Pause and Mute State Management Source: https://context7.com/wanted5games/unity-game-interface-package/llms.txt Provides methods to check and apply pause and mute states, and to report player-initiated mute changes back to the platform. ```APIDOC ## Pause & Mute State ### Description Manages the game's pause and mute states. `IsPaused()` and `IsMuted()` retrieve the current state, while `GameMuted(bool)` reports player-initiated audio changes. ### Methods - **IsPaused()**: Returns `true` if the game is currently paused, `false` otherwise. - **IsMuted()**: Returns `true` if the game's audio is currently muted, `false` otherwise. - **GameMuted(bool isMuted)**: Reports player-initiated mute changes to the platform. Call this when the player interacts with a mute control. - **OnPauseStateChange**: Event triggered when the pause state changes. - **OnMuteStateChange**: Event triggered when the mute state changes. ### Example Usage (C#) ```csharp // Check and apply states on enable if (GameInterface.Instance.IsPaused()) ApplyPause(true); if (GameInterface.Instance.IsMuted()) ApplyMute(true); // Subscribe to state changes GameInterface.Instance.OnPauseStateChange += ApplyPause; GameInterface.Instance.OnMuteStateChange += ApplyMute; // Report player mute toggle public void OnPlayerToggleMute(bool nowMuted) { AudioListener.volume = nowMuted ? 0f : 1f; GameInterface.Instance.GameMuted(nowMuted); } ``` ``` -------------------------------- ### Control UI Elements with Feature Flags Source: https://context7.com/wanted5games/unity-game-interface-package/llms.txt Conditionally enables/disables UI elements based on available features. Fetches language and copyright logo URL. ```csharp public class UIController : MonoBehaviour { [SerializeField] private GameObject muteButton; [SerializeField] private GameObject pauseButton; [SerializeField] private GameObject scoreDisplay; [SerializeField] private GameObject shopButton; [SerializeField] private GameObject copyrightLogo; private void Start() { var gi = GameInterface.Instance; muteButton.SetActive(gi.HasFeature("audio")); pauseButton.SetActive(gi.HasFeature("pause")); scoreDisplay.SetActive(gi.HasFeature("score")); shopButton.SetActive(gi.HasFeature("iap")); copyrightLogo.SetActive(gi.HasFeature("copyright")); string lang = gi.GetCurrentLanguage(); // "en", "de", "fr", etc. LocalizationManager.SetLanguage(lang); if (gi.HasFeature("copyright")) { string logoUrl = gi.GetCopyrightLogoURL("medium", "dark"); // 128x128 light logo StartCoroutine(LoadLogoCoroutine(logoUrl)); } } private IEnumerator LoadLogoCoroutine(string url) { // Load the logo sprite from URL and assign to Image component yield return null; } } ``` -------------------------------- ### Famobi.json Editor Source: https://github.com/wanted5games/unity-game-interface-package/blob/main/README.md Manage ad eventIds and IAP products using the Famobi.json Editor window in Unity. This avoids direct JSON file editing and ensures all necessary configurations are correctly set. ```APIDOC ## famobi.json The `famobi.json` file is required for your game and must be located in the WebGL template folder (`Assets/WebGLTemplates/GameInterface/famobi.json`). This file lists all ad eventIds and IAP products used in your game. **Instead of editing the JSON file directly**, you can use the **Famobi.json Editor** window: 1. Open **Game Interface ▸ Famobi.json Editor** from the Unity menu bar 2. Edit your ad eventIds (interstitial and rewarded) 3. Edit your IAP products (SKU, title, description, image URI, price) ![FamobiJSONEditorWindow](Documentation/FamobiJsonEditorWindow.png) ⚠️ **Important**: - All eventIds used in your game must be listed in this file. See the [documentation](https://docs.famobi.com/ads) for details. - IAP products defined in `famobi.json` are automatically loaded and merged with API results when calling `GetProducts()`. Products are shuffled for each call. ``` -------------------------------- ### Game Interface Storage System Source: https://github.com/wanted5games/unity-game-interface-package/blob/main/README.md Utilize the GameInterface storage system for automatic caching, size monitoring, and configurable limits. Store and retrieve data using SetStorageItem and GetStorageItem, and clear storage with ClearStorage. ```C# // Store data (automatically cached) GameInterface.Instance.SetStorageItem("playerName", "Player1"); GameInterface.Instance.SetStorageItem("highScore", 1000); // Retrieve data (uses cache if available) string name = GameInterface.Instance.GetStorageItem("playerName"); int score = GameInterface.Instance.GetStorageItem("highScore"); // Clear storage GameInterface.Instance.ClearStorage(); ``` -------------------------------- ### Storage Operations Source: https://context7.com/wanted5games/unity-game-interface-package/llms.txt Manage game data using SetStorageItem, GetStorageItem, RemoveItem, and ClearStorage. Supports primitives and JSON-serializable objects with configurable limits. ```APIDOC ## Storage Operations Replaces Unity `PlayerPrefs` with a platform-aware storage system that includes in-memory caching and size monitoring. Supports primitives (`string`, `int`, `float`, `bool`) and JSON-serializable objects. Default limits are 1 MB per item and 1 MB total. ### SetStorageItem Stores a value in the game's storage. Can store primitives or JSON-serializable objects. ```csharp GameInterface.Instance.SetStorageItem(string key, object value); ``` ### GetStorageItem Retrieves a value from storage, attempting to cast it to the specified type `T`. Uses in-memory cache if available. ```csharp T GameInterface.Instance.GetStorageItem(string key); ``` ### RemoveItem Removes a specific item from storage by its key. ```csharp GameInterface.Instance.RemoveItem(string key); ``` ### ClearStorage Removes all items from the game's storage. ```csharp GameInterface.Instance.ClearStorage(); ``` ### Configuration Set custom storage limits. ```csharp // Set max item size to 512 KB GameInterface.Instance.MaxStorageItemBytes = 512 * 1024; // Set max total storage size to 2 MB GameInterface.Instance.MaxTotalStorageBytes = 2 * 1024 * 1024; ``` ``` -------------------------------- ### Handle Banner Offsets and Resize Canvas Source: https://context7.com/wanted5games/unity-game-interface-package/llms.txt Use GetOffsets to retrieve banner area dimensions and OnOffsetChange to react to changes. ResizeGameCanvas automatically adjusts the WebGL canvas to accommodate banner offsets. ```csharp public class CanvasResizer : MonoBehaviour { private void OnEnable() { GameInterface.Instance.OnOffsetChange += HandleOffsetChange; // Apply initial offsets HandleOffsetChange(GameInterface.Instance.GetOffsets()); } private void OnDisable() { GameInterface.Instance.OnOffsetChange -= HandleOffsetChange; } private void HandleOffsetChange(OffsetResult offsets) { // Resize the Unity WebGL canvas to respect banner space GameInterface.Instance.ResizeGameCanvas(); Debug.Log($"Offsets — top:{offsets.top} bottom:{offsets.bottom} " + $ ``` -------------------------------- ### Banner Offsets Source: https://context7.com/wanted5games/unity-game-interface-package/llms.txt Retrieve banner offsets and resize the game canvas accordingly. Handles changes in banner visibility and size. ```APIDOC ## Banner Offsets — GetOffsets / OnOffsetChange / ResizeGameCanvas ### Description Provides functionality to get current banner offsets, subscribe to offset change events, and resize the game canvas to accommodate banners. ### Methods - `GetOffsets()`: Returns the current reserved banner area (`top`, `bottom`, `left`, `right` in pixels). - `OnOffsetChange(Action callback)`: Event that fires when banner offsets change. - `ResizeGameCanvas()`: Automatically adjusts the WebGL canvas to account for banner offsets. ### Usage Example ```csharp // Get current offsets OffsetResult offsets = GameInterface.Instance.GetOffsets(); Debug.Log($"Offsets — top:{offsets.top} bottom:{offsets.bottom} left:{offsets.left} right:{offsets.right}"); // Subscribe to offset changes GameInterface.Instance.OnOffsetChange += HandleOffsetChange; // Resize canvas GameInterface.Instance.ResizeGameCanvas(); // Example handler void HandleOffsetChange(OffsetResult offsets) { GameInterface.Instance.ResizeGameCanvas(); // ... additional UI adjustments ... } ``` ``` -------------------------------- ### Progress and Score Reporting Source: https://context7.com/wanted5games/unity-game-interface-package/llms.txt Report player progress as a percentage (0-100) and the current score during gameplay. These methods are fire-and-forget. ```APIDOC ## SendProgress / SendScore ### Description Reports player progress as a percentage (0–100) during gameplay using `SendProgress(int)`. Reports the current score using `SendScore(int)`. Both are fire-and-forget operations. ### Methods - `SendProgress(int progress)`: Reports player progress. - `SendScore(int score)`: Reports the current score. ### Usage Example ```csharp // Assuming GameInterface.Instance is accessible GameInterface.Instance.SendScore(100); GameInterface.Instance.SendProgress(50); ``` ``` -------------------------------- ### Manage Ad Events and Availability Source: https://context7.com/wanted5games/unity-game-interface-package/llms.txt Handle interstitial and rewarded ad calls asynchronously. Use IsRewardedAdAvailable for synchronous checks to update button visibility. Subscribe to OnRewardedAdAvailabilityChange for real-time updates. ```csharp public class AdManager : MonoBehaviour { [SerializeField] private GameObject rewardButton; private void OnEnable() { GameInterface.Instance.OnRewardedAdAvailabilityChange += HandleRewardedAvailability; // Initialize button state rewardButton.SetActive(GameInterface.Instance.IsRewardedAdAvailable("button:example:test")); } private void OnDisable() { GameInterface.Instance.OnRewardedAdAvailabilityChange -= HandleRewardedAvailability; } private void HandleRewardedAvailability(string eventId, bool isAvailable) { rewardButton.SetActive(isAvailable); } // Interstitial ad on button press (callback pattern) public async void ShowInterstitialOnQuit() { await GameInterface.Instance.ShowInterstitialAd( eventId: "button:menu:start", placementType: "quit", onAdClosed: () => Debug.Log("Interstitial closed"), onAdFailed: err => Debug.LogWarning($"Interstitial failed: {err}") ); } // Rewarded ad with async/await public async void ShowRewardedAd() { try { var result = await GameInterface.Instance.ShowRewardedAd( eventId: "button:example:test", onAdClosed: r => Debug.Log($"Reward granted: {r.isRewardGranted}") ); if (result.isRewardGranted) GivePlayerReward(); } catch (Exception e) { Debug.LogError($"Rewarded ad failed: {e.Message}"); } } // Async availability check (snapshot) public async void CheckAvailability() { bool available = await GameInterface.Instance.HasRewardedAd("button:example:test"); rewardButton.SetActive(available); } private void GivePlayerReward() { /* grant reward logic */ } } ``` -------------------------------- ### Feature Flags Source: https://context7.com/wanted5games/unity-game-interface-package/llms.txt Provides functionality to check for the availability of specific features on the current platform and retrieve configuration settings. ```APIDOC ## Feature Flags ### Description Provides functionality to check for the availability of specific features on the current platform and retrieve configuration settings. ### Methods - **HasFeature(string featureName)**: Returns `true` if the specified feature is enabled, `false` otherwise. Useful for conditionally displaying UI elements. - **GetCurrentLanguage()**: Returns the current locale string (e.g., "en", "de"). - **GetCopyrightLogoURL(string size, string theme)**: Retrieves the URL for the copyright logo, with specified size and theme. ``` -------------------------------- ### In-App Purchases Source: https://context7.com/wanted5games/unity-game-interface-package/llms.txt Manages in-app purchase operations including retrieving product details, initiating purchases, and consuming products. It also handles events related to purchase status. ```APIDOC ## In-App Purchases ### Description Manages in-app purchase operations including retrieving product details, initiating purchases, and consuming products. It also handles events related to purchase status. ### Methods - **GetProducts(Action onComplete, Action onError)**: Retrieves a list of available in-app products. Should be called once at startup. - **BuyProduct(string sku, Action onComplete, Action onError)**: Initiates the purchase flow for a given product SKU. - **ConsumeProduct(PurchaseDetail purchase, Action onComplete)**: Consumes a purchased product, typically after granting the user the content. - **OnIAPEvent**: An event that fires with `IAPEvent` data, containing details about purchase success, failure, or consumption. ### Events - **"PURCHASE_SUCCESS_EVENT"**: Fired when a purchase is successfully completed. - **"PURCHASE_FAIL_EVENT"**: Fired when a purchase is cancelled or fails. - **"CONSUME_SUCCESS_EVENT"**: Fired when a product consumption is confirmed. ### Usage Flow 1. Call `GetProducts()` at startup. 2. Call `BuyProduct(sku)` to initiate a purchase. 3. Handle `OnIAPEvent` for `"PURCHASE_SUCCESS_EVENT"`. 4. Grant the user the purchased content. 5. Call `ConsumeProduct()` to finalize the transaction. ``` -------------------------------- ### Visibility Change Source: https://context7.com/wanted5games/unity-game-interface-package/llms.txt Handles and detects changes in the application's visibility, such as when the browser tab is hidden or shown. ```APIDOC ## Visibility Change ### Description Handles and detects changes in the application's visibility, such as when the browser tab is hidden or shown. ### Methods - **InitVisibilityChange()**: Registers the JavaScript visibility listener to enable tracking of tab visibility changes. - **IsHidden()**: Returns the current visibility state of the application tab (`true` if hidden, `false` otherwise). ### Events - **OnVisibilityChange**: An event that fires with a boolean value indicating whether the application tab is hidden (`true`) or shown (`false`). ``` -------------------------------- ### Control Splash Screen and Canvas Source: https://github.com/wanted5games/unity-game-interface-package/blob/main/README.md Use GameInterface.Instance.DisableSplashScreen() to disable the custom splash screen. Call GameInterface.Instance.InitVisibilityChange() to initialize an event listener for visibility changes. Resize the game canvas with GameInterface.Instance.ResizeGameCanvas(). ```C# // Disable the custom splash screen. GameInterface.Instance.DisableSplashScreen(); // Initialize an event listener for visibility changes (if supported by the platform). GameInterface.Instance.InitVisibilityChange(); // Resize the game canvas, applying the offset for the banner. GameInterface.Instance.ResizeGameCanvas(); ``` -------------------------------- ### Ad Events Source: https://context7.com/wanted5games/unity-game-interface-package/llms.txt Manage interstitial and rewarded ad display, and check ad availability. Ad calls are asynchronous and use event IDs. ```APIDOC ## Ad Events — ShowInterstitialAd / ShowRewardedAd / HasRewardedAd / IsRewardedAdAvailable ### Description Handles interstitial and rewarded ad display, ad availability checks, and callbacks for ad events. Interstitial and rewarded ad calls are async and use event IDs. `IsRewardedAdAvailable` is synchronous and `OnRewardedAdAvailabilityChange` fires when availability changes. ### Methods - `ShowInterstitialAd(string eventId, string placementType, Action onAdClosed, Action onAdFailed)`: Displays an interstitial ad. - `ShowRewardedAd(string eventId, Action onAdClosed)`: Displays a rewarded ad. - `HasRewardedAd(string eventId)`: Asynchronously checks if a rewarded ad is available. - `IsRewardedAdAvailable(string eventId)`: Synchronously checks if a rewarded ad is available. - `OnRewardedAdAvailabilityChange(Action callback)`: Event that fires when rewarded ad availability changes. ### Usage Example ```csharp // Show an interstitial ad await GameInterface.Instance.ShowInterstitialAd( eventId: "button:menu:start", placementType: "quit", onAdClosed: () => Debug.Log("Interstitial closed"), onAdFailed: err => Debug.LogWarning($"Interstitial failed: {err}") ); // Show a rewarded ad var result = await GameInterface.Instance.ShowRewardedAd( eventId: "button:example:test", onAdClosed: r => Debug.Log($"Reward granted: {r.isRewardGranted}") ); // Check rewarded ad availability bool available = await GameInterface.Instance.HasRewardedAd("button:example:test"); ``` ``` -------------------------------- ### Analytics Tracking: Track Events Source: https://context7.com/wanted5games/unity-game-interface-package/llms.txt Sends GameAnalytics events to the platform. Use GAEventType for event category and provide an optional data dictionary. Ensure the event key is GAEventType when using a full dictionary. ```csharp public class AnalyticsManager : MonoBehaviour { // Using GAEventType + data dictionary public void TrackLevelStart(int level) { GameInterface.Instance.Track(GAEventType.PROGRESSION, new Dictionary { { "eventId", $"Game:Start:Level_{level}" }, }); } // Using full dictionary (event key must be GAEventType) public void TrackPurchase(string sku, float price) { GameInterface.Instance.Track(new Dictionary { { "event", GAEventType.BUSINESS }, { "eventId", $"Purchase:{sku}" }, { "amount", (int)(price * 100) }, // in cents { "currency", "USD" }, }); } // Track an error public void TrackError(string message) { GameInterface.Instance.Track(GAEventType.ERROR, new Dictionary { { "message", message }, }); } } // Available GAEventType values: // GAEventType.BUSINESS, PROGRESSION, RESOURCE, ERROR, DESIGN ``` -------------------------------- ### Analytics Tracking Source: https://context7.com/wanted5games/unity-game-interface-package/llms.txt Send game analytics events using the Track method. Supports predefined event types and custom data dictionaries. ```APIDOC ## Analytics Tracking — Track `Track` sends GameAnalytics events to the platform. Use `GAEventType` to specify the event category and provide an optional data dictionary. ### Track with GAEventType and Dictionary Sends an event with a predefined category and a custom data dictionary. ```csharp GameInterface.Instance.Track(GAEventType eventType, Dictionary data); ``` ### Track with Full Dictionary Sends an event using a complete data dictionary where the event type is specified by the `event` key. ```csharp GameInterface.Instance.Track(Dictionary data); ``` ### Available GAEventType Values - `GAEventType.BUSINESS` - `GAEventType.PROGRESSION` - `GAEventType.RESOURCE` - `GAEventType.ERROR` - `GAEventType.DESIGN` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.