### Start Network Monitoring and Handle Connectivity Changes Source: https://assetstore.essentialkit.voxelbusters.com/features/network-services/usage This code initializes network monitoring using `NetworkServices.StartNotifier()` and provides example callback functions to handle changes in internet connectivity and host reachability. It logs appropriate messages based on the connection status. ```csharp void Start() { // Start monitoring network status NetworkServices.StartNotifier(); Debug.Log("Network monitoring started"); } void OnInternetConnectivityChange(NetworkServicesInternetConnectivityStatusChangeResult result) { if (result.IsConnected) { Debug.Log("Internet connected"); Debug.Log("Enable online-only features."); Debug.Log("Show connected indicator."); } else { Debug.Log("Internet disconnected"); Debug.Log("Disable online-only features."); Debug.Log("Show offline indicator."); } } void OnHostReachabilityChange(NetworkServicesHostReachabilityStatusChangeResult result) { if (result.IsReachable) { Debug.Log("Backend server reachable"); Debug.Log("Unlock server-powered features."); } else { Debug.Log("Backend server unreachable"); Debug.Log("Inform players about server maintenance."); } } ``` -------------------------------- ### Example Product Configuration for Essential Kit Source: https://assetstore.essentialkit.voxelbusters.com/features/billing-services/setup Defines the structure for product configurations including ID, type, and platform-specific IDs for consumables, non-consumables, and subscriptions. ```yaml Product 1: Id: coins_100 Type: Consumable iOS ID: com.yourgame.coins_100 Android ID: com.yourgame.coins_100 Product 2: Id: remove_ads Type: NonConsumable iOS ID: com.yourgame.remove_ads Android ID: com.yourgame.remove_ads Product 3: Id: vip_monthly Type: Subscription iOS ID: com.yourgame.vip_monthly Android ID: com.yourgame.vip_monthly ``` -------------------------------- ### Opening Application Settings Source: https://assetstore.essentialkit.voxelbusters.com/features/utilities/usage This section explains how to direct users to their device's system settings for the application. ```APIDOC ## POST /api/utilities/openApplicationSettings ### Description Opens the system settings for the current application. This is useful for guiding users to re-enable permissions or manage app settings when they have been denied. ### Method POST ### Endpoint /api/utilities/openApplicationSettings ### Parameters None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the operation. #### Response Example ```json { "status": "Application settings opened successfully" } ``` ``` -------------------------------- ### WebView Manual Initialization Source: https://assetstore.essentialkit.voxelbusters.com/features/web-view/usage Advanced guide for manually initializing WebView with custom settings, overriding the default automatic initialization. ```APIDOC ## WebView Manual Initialization (Advanced) ### Description This section covers advanced scenarios requiring manual initialization of the WebView component, allowing for runtime configuration overrides. {% hint style="warning" %} Manual initialization is typically only necessary for specific runtime requirements. For most applications, Essential Kit's automatic initialization, configured via the Unity Editor, is sufficient. Proceed with manual initialization only if you need runtime configuration or per-instance custom settings. {% endhint %} ### Understanding Manual Initialization **Default Behavior:** Essential Kit automatically initializes the WebView using global settings defined in the ScriptableObject configured within the Unity Editor. **Advanced Usage:** Manual initialization allows you to override these settings at runtime or on a per-instance basis for scenarios such as: * Dynamically adjusting camera/microphone permissions based on web content. * Implementing different back button behaviors for distinct web views. * Receiving server-driven feature configurations. ### Implementation **1. Configuring Global Settings (Awake Method):** Initialize the WebView system with global settings before creating any instances. This is usually done once at the start of your application or scene. ```csharp using UnityEngine; // Assuming WebViewUnitySettings and WebView are accessible void Awake() { var globalSettings = new WebViewUnitySettings( isEnabled: true, androidProperties: new WebViewUnitySettings.AndroidPlatformProperties() { UsesCamera = true, UsesMicrophone = false, AllowBackNavigationKey = true } ); WebView.Initialize(globalSettings); } ``` **2. Creating an Instance with Custom Settings:** You can create individual WebView instances with settings that override the global configuration. ```csharp // Assuming 'webView' is a member variable of type WebView void CreateCustomWebView() { var instanceSettings = new WebViewUnitySettings( isEnabled: true, androidProperties: new WebViewUnitySettings.AndroidPlatformProperties() { UsesCamera = false, // Overrides the global setting UsesMicrophone = false, AllowBackNavigationKey = false } ); webView = WebView.CreateInstance(instanceSettings); } ``` {% hint style="info" %} Ensure that `WebView.Initialize()` is called *before* any `WebView.CreateInstance()` calls. For standard game setups, it is recommended to use the [standard setup](https://assetstore.essentialkit.voxelbusters.com/features/web-view/setup) configured in the Essential Kit Settings asset instead of manual initialization. {% endhint %} ``` -------------------------------- ### Install Downloaded Update (Android) Source: https://assetstore.essentialkit.voxelbusters.com/features/app-updater/usage This C# code shows how to install a downloaded update when the update status is 'Downloaded'. It uses `PromptUpdateOptions.Builder` to customize the update prompt and handles the installation process directly if the update is already downloaded. ```csharp void InstallDownloadedUpdate() { var options = new PromptUpdateOptions.Builder() .SetPromptTitle("Install Update") .SetPromptMessage("Update is ready to install. App will restart.") .SetAllowInstallationIfDownloaded(true) .Build(); AppUpdater.PromptUpdate(options, (progress, error) => { if (error == null && progress >= 1.0f) { Debug.Log("Installing update..."); } }); } ``` -------------------------------- ### Multi-Currency Payout Definition Example Source: https://assetstore.essentialkit.voxelbusters.com/features/billing-services/setup Illustrates the YAML structure for defining multiple virtual currency payouts associated with a single product purchase in Essential Kit. ```yaml Product: mega_pack Payouts: - Type: coins, Quantity: 500 - Type: gems, Quantity: 100 - Type: tickets, Quantity: 25 ``` -------------------------------- ### Manual Native UI Initialization in C# Source: https://assetstore.essentialkit.voxelbusters.com/features/native-ui/usage Demonstrates how to manually initialize Native UI with custom settings at runtime. This is useful for advanced scenarios like custom themes or runtime configuration, but manual initialization is generally not recommended for most games. ```csharp void Awake() { var settings = new NativeUIUnitySettings(isEnabled: true); // Configure advanced settings if needed (custom UI collection, etc.) NativeUI.Initialize(settings); } ``` -------------------------------- ### Server Push Notification Payload Examples Source: https://assetstore.essentialkit.voxelbusters.com/features/notification-services/usage Provides example server payloads for sending push notifications to Android (FCM) and iOS (APNS) devices. These examples include basic alert messages and custom user information for testing purposes. ```json { "to": "device_token_here", "data": { "content_title": "Flash Sale!", "content_text": "50% off gem packs for the next 2 hours!", "ticker_text": "Limited time offer", "tag": "flash_sale", "badge": 1, "user_info": { "offer_id": "gems_50_off", "expires": "2024-10-06T10:00:00Z" } } } ``` ```json { "aps": { "alert": { "title": "Flash Sale!", "body": "50% off gem packs for the next 2 hours!" }, "badge": 1, "sound": "default" }, "user_info": { "offer_id": "gems_50_off", "expires": "2024-10-06T10:00:00Z" } } ``` -------------------------------- ### Calendar Trigger Examples (C#) Source: https://assetstore.essentialkit.voxelbusters.com/features/notification-services/usage Provides examples of creating various calendar triggers, including daily, weekly, monthly, and annual notifications, using the DateComponents class. ```csharp // Daily notification at specific time var daily = new DateComponents(); daily.Hour = 18; // 6 PM daily.Minute = 0; // Weekly notification (Monday at 9 AM) var weekly = new DateComponents(); weekly.DayOfWeek = 1; // Monday (ISO 8601: 1=Monday, 7=Sunday) weekly.Hour = 9; weekly.Minute = 0; // Monthly notification (15th of each month at noon) var monthly = new DateComponents(); monthly.Day = 15; monthly.Hour = 12; monthly.Minute = 0; // Annual notification (birthday, anniversary) var annual = new DateComponents(); annual.Month = userBirthday.Month; annual.Day = userBirthday.Day; annual.Hour = 9; annual.Minute = 0; ``` -------------------------------- ### Initialize Store Connection and Retrieve Products (C#) Source: https://assetstore.essentialkit.voxelbusters.com/features/billing-services/usage Connects to platform stores to initialize the billing service and retrieve available product information. This function is crucial for fetching current pricing and availability. It logs the initialization status and lists product titles and prices. Dependencies include the BillingServices class and Debug logging. ```csharp void Start() { BillingServices.InitializeStore(); Debug.Log("Initializing store..."); } void OnStoreInitialized(BillingServicesInitializeStoreResult result, Error error) { if (error != null) { Debug.LogError($"Store init failed: {error.Description}"); return; } Debug.Log($"Store ready with {result.Products.Length} products"); foreach (var product in result.Products) { Debug.Log($"{product.LocalizedTitle} - {product.LocalizedPrice}"); } } ``` -------------------------------- ### Runtime Initialization Source: https://assetstore.essentialkit.voxelbusters.com/features/app-shortcuts/usage Advanced guide on manually initializing App Shortcuts at runtime, overriding default settings for dynamic icon configurations. ```APIDOC ## POST /api/shortcuts/initialize ### Description Manually initialize the App Shortcuts system at runtime. This is typically used when dynamic configuration of shortcut icons is needed based on server data or user preferences, overriding the default initialization from Essential Kit Settings. ### Method POST ### Endpoint /api/shortcuts/initialize ### Parameters #### Request Body - **settings** (object) - Required - An object containing the runtime settings for App Shortcuts. - **isEnabled** (boolean) - Required - Whether the App Shortcuts feature is enabled. - **icons** (array) - Required - A list of runtime icon configurations. Each item should define properties like identifier, title, subtitle, and icon file name. ### Request Example ```json { "settings": { "isEnabled": true, "icons": [ { "id": "dynamic-shortcut-1", "title": "Dynamic Feature A", "subtitle": "Access feature A", "iconFileName": "feature_a.png" }, { "id": "dynamic-shortcut-2", "title": "Dynamic Feature B", "subtitle": "Access feature B", "iconFileName": "feature_b.png" } ] } } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message that initialization was successful. #### Response Example ```json { "message": "App Shortcuts initialized successfully with runtime settings." } ``` ### Guidelines - Call `Initialize` once before adding or removing shortcuts. - Avoid calling `Initialize` multiple times during gameplay as it replaces the native interface. - This method should ideally be called during application startup (e.g., in `Awake`) before any shortcuts are added. ``` -------------------------------- ### Initiate Interactive Player Authentication Source: https://assetstore.essentialkit.voxelbusters.com/features/game-services/usage Starts the player authentication process. If the player is not already signed in, this method will display the platform's native login UI (Game Center or Google Play Games). It logs the start of the process. ```csharp void SignInPlayer() { Debug.Log("Starting authentication..."); GameServices.Authenticate(interactive: true); } ``` -------------------------------- ### Runtime Product Configuration (C#) Source: https://assetstore.essentialkit.voxelbusters.com/features/billing-services/usage Initializes billing services at runtime with custom product definitions, allowing for server-driven catalogs, A/B testing, and dynamic pricing. This overrides the default settings asset. ```csharp void ConfigureProductsAtRuntime() { var products = new[] { new BillingProductDefinition( id: "coins_100", platformId: "coins_100", platformIdOverrides: new RuntimePlatformConstantSet( ios: "com.yourgame.coins_100", android: "coins_100"), productType: BillingProductType.Consumable, title: "100 Coins", description: "Grants 100 soft currency coins") }; var settings = new BillingServicesUnitySettings( products: products, autoFinishTransactions: true); BillingServices.Initialize(settings); } ``` -------------------------------- ### Configure Platform IDs in C# (Essential Kit) Source: https://assetstore.essentialkit.voxelbusters.com/features/game-services/notes/migration-guide-from-google-play-games-plugin-for-unity-to-essential-kit-game-services Provides a solution for the common issue of missing platform IDs. It guides the user to the configuration settings within the Essential Kit for proper setup, preventing authentication failures. ```csharp // SOLUTION: Ensure all platform IDs are configured in Essential Kit settings // Check Window → Voxel Busters → Essential Kit → Configure ``` -------------------------------- ### Account Change Event (Unity C#) Source: https://assetstore.essentialkit.voxelbusters.com/features/cloud-services/testing Example of handling the OnSavedDataChange event with the AccountChange reason. This verifies that data is correctly isolated between different cloud accounts. ```csharp void OnSavedDataChange(SavedDataChangeEventArgs args) { if (args.reason == SavedDataChangeReason.AccountChange) { // Handle account switch: clear old data, load new data } } ``` -------------------------------- ### Create a WebView Instance Source: https://assetstore.essentialkit.voxelbusters.com/features/web-view/usage This snippet illustrates how to create a new instance of the WebView. Essential Kit follows a single-instance model, meaning only one active web view can exist at a time. Creating a new instance will replace any existing one. ```csharp private WebView webView; void Start() { // Create web view instance webView = WebView.CreateInstance(); Debug.Log("WebView instance created"); } ``` -------------------------------- ### Set and Get Test Data (Unity C#) Source: https://assetstore.essentialkit.voxelbusters.com/features/cloud-services/testing Demonstrates how to set and retrieve string data using the CloudServices API. This is useful for validating data persistence and synchronization. ```csharp CloudServices.SetString("test_key", "test_value"); string retrievedValue = CloudServices.GetString("test_key"); // Verify retrievedValue matches "test_value" ``` -------------------------------- ### Getting Notification Settings Source: https://assetstore.essentialkit.voxelbusters.com/features/notification-services/usage Retrieves the current notification permission status and settings. This is an optional method, and the settings are returned asynchronously via a callback function as a NotificationSettings object. ```javascript NotificationServices.GetSettings(callback); ``` -------------------------------- ### Iterate Through Product Offers in C# Source: https://assetstore.essentialkit.voxelbusters.com/features/billing-services/usage This code iterates through all available offers for products obtained after initializing the store. It logs offer IDs, categories, and pricing phase details. This assumes `InitializeStore()` has been called and `result.Products` is populated. ```csharp foreach (var product in result.Products) { if (product.Offers != null && product.Offers.Length > 0) { foreach (var offer in product.Offers) { Debug.Log($"Offer: {offer.Id}, Category: {offer.Category}"); foreach (var phase in offer.PricingPhases) { Debug.Log($" Phase: {phase.Price}, Mode: {phase.PaymentMode}"); } } } } ``` -------------------------------- ### Override Network Services Settings at Runtime (C#) Source: https://assetstore.essentialkit.voxelbusters.com/features/network-services/usage Demonstrates how to initialize Network Services with custom settings before starting monitoring. This allows for dynamic configuration of host address, ping settings, and other parameters. Ensure `Initialize()` is called before `StartNotifier()`. ```csharp void Awake() { var customSettings = new NetworkServicesUnitySettings( isEnabled: true, hostAddress: new Address { IPv4 = "api.mygame.com", IPv6 = string.Empty }, autoStartNotifier: false, pingSettings: new NetworkServicesUnitySettings.PingTestSettings( maxRetryCount: 3, timeGapBetweenPolling: 5f, timeOutPeriod: 10f, port: 443)); NetworkServices.Initialize(customSettings); } ``` -------------------------------- ### Add Custom Data to Notification (C#) Source: https://assetstore.essentialkit.voxelbusters.com/features/notification-services/usage Attaches custom key-value string data to a notification, enabling deep linking and event identification. The example demonstrates adding tournament details. ```csharp var notification = NotificationBuilder.CreateNotification("tournament_start") .SetTitle("Tournament Starting Soon!") .SetBody("PvP Tournament begins in 1 hour. Prepare for battle!") .SetUserInfo(new Dictionary { ["type"] = "tournament_reminder", ["tournament_id"] = "pvp_2024_10", ["deep_link"] = "mygame://tournaments/pvp_2024_10" }) .SetTimeIntervalNotificationTrigger(3600) .Create(); ``` -------------------------------- ### Launch Deep Link via ADB (Android) Source: https://assetstore.essentialkit.voxelbusters.com/features/deep-link-services/testing This ADB command launches a deep link on an Android device or emulator. It utilizes the `am start` command with the `android.intent.action.VIEW` action to open the specified URL. ```bash adb shell am start -W -a android.intent.action.VIEW -d "mygame://invite/friend123" ``` -------------------------------- ### Get Delivered Notifications (C#) Source: https://assetstore.essentialkit.voxelbusters.com/features/notification-services/usage Retrieves and logs the notifications currently displayed in the device's notification center. Uses a callback to handle the results and displays the number of notifications retrieved. ```csharp NotificationServices.GetDeliveredNotifications((result, error) => { if (error == null) { INotification[] delivered = result.Notifications; Debug.Log($"Notifications in notification center: {delivered.Length}"); } }); ``` -------------------------------- ### Manually Initialize Media Services in C# Source: https://assetstore.essentialkit.voxelbusters.com/features/media-services/usage This C# code snippet shows how to manually initialize Essential Kit's Media Services with custom settings before they are used. This is an advanced feature useful for runtime configuration overrides. ```csharp void Awake() { var customSettings = new MediaServicesUnitySettings( isEnabled: true, usesCameraForImageCapture: true, usesCameraForVideoCapture: true, savesFilesToGallery: true, savesFilesToCustomAlbums: false); // Disable custom albums MediaServices.Initialize(customSettings); } ``` -------------------------------- ### Custom Runtime Initialization (C#) Source: https://assetstore.essentialkit.voxelbusters.com/features/utilities/usage Demonstrates how to manually initialize Essential Kit Utilities at runtime, typically for advanced scenarios like loading settings from remote configurations or environment-specific behaviors. This is an alternative to using the ScriptableObject for settings. ```csharp void Awake() { var settings = new UtilityUnitySettings(isEnabled: true); // Configure additional options here if new fields are added in future versions Utilities.Initialize(settings); } ``` -------------------------------- ### Time Interval Notification Triggers (C#) Source: https://assetstore.essentialkit.voxelbusters.com/features/notification-services/usage Defines notification triggers based on time intervals. Examples show firing once after a set duration, repeating daily, or using TimeSpan for precise timing. ```csharp // Fire once after 1 hour .SetTimeIntervalNotificationTrigger(3600) // Fire every 24 hours (daily) .SetTimeIntervalNotificationTrigger(86400, repeats: true) // Fire once after 30 minutes .SetTimeIntervalNotificationTrigger(TimeSpan.FromMinutes(30).TotalSeconds) ``` -------------------------------- ### Handling Billing Transactions Source: https://assetstore.essentialkit.voxelbusters.com/migrations/gley/easy-iap/migration-guide This example outlines the callback signature for handling transaction state changes in Essential Kit. It replaces the `OnPurchase` callback from Gley Easy IAP, providing detailed transaction results. ```csharp void HandleTransactions(BillingServicesTransactionStateChangeResult transaction); ``` -------------------------------- ### Get Scheduled Notifications (C#) Source: https://assetstore.essentialkit.voxelbusters.com/features/notification-services/usage Retrieves and displays all pending scheduled notifications. It uses a callback to handle the result, logging the total number of notifications and their titles. It's useful for checking what notifications are scheduled. ```csharp NotificationServices.GetScheduledNotifications((result, error) => { if (error == null) { INotification[] notifications = result.Notifications; Debug.Log($"Total scheduled: {notifications.Length}"); foreach (var notification in notifications) { Debug.Log($"{notification.Id}: {notification.Title}"); } } }); ``` -------------------------------- ### Initialize Store and Check Payment Capability in C# Source: https://assetstore.essentialkit.voxelbusters.com/features/billing-services/usage Demonstrates core Essential Kit billing API calls in C#. Includes initializing the store, checking if payments are possible, and verifying if a product has already been purchased. These are fundamental steps for integrating in-app purchases. ```csharp // Connect to store and fetch products BillingServices.InitializeStore(); // Check if purchases allowed if (BillingServices.CanMakePayments()) { // Proceed with purchase logic } // Check ownership (non-consumables/subs only) // bool isPurchased = BillingServices.IsProductPurchased("your_product_id"); ``` -------------------------------- ### Tracking Engagement Signals Source: https://assetstore.essentialkit.voxelbusters.com/features/rate-my-app/usage This section explains how to track significant player events to determine when to prompt for a review. It provides a C# code example using PlayerPrefs to count events and conditionally call `AskForReviewNow`. ```APIDOC ## Tracking Engagement Signals Rate prompts feel earned when you tie them to positive experiences. Track those signals and only call `AskForReviewNow` when the player is immersed. ```csharp private const string kSignificantEventsKey = "rma_significant_events"; void OnAchievementUnlocked() { Debug.Log("Achievement unlocked!"); int totalEvents = PlayerPrefs.GetInt(kSignificantEventsKey, 0) + 1; PlayerPrefs.SetInt(kSignificantEventsKey, totalEvents); PlayerPrefs.Save(); if (RateMyApp.IsAllowedToRate()) { RateMyApp.AskForReviewNow(skipConfirmation: false); } } ``` You can replace the `PlayerPrefs` logic with your analytics stack or backend-driven counters—what matters is deferring the prompt until the player hits the milestones you care about. ``` -------------------------------- ### WebView Instance Management API Source: https://assetstore.essentialkit.voxelbusters.com/features/web-view/usage APIs for creating, configuring, and managing WebView instances. ```APIDOC ## WebView Instance Management API ### Description Provides methods for creating, configuring, and managing WebView instances. ### API Reference - **`WebView.CreateInstance(settings)`** - **Purpose**: Create a new web view instance. - **Parameters**: - `settings` (WebViewUnitySettings) - Optional settings for the new web view instance. - **Returns**: `WebView` instance. - **`webView.SetFullScreen()`** - **Purpose**: Set the web view to full screen. - **Returns**: void. - **`webView.SetNormalizedFrame(rect)`** - **Purpose**: Set the size of the web view using normalized coordinates. - **Parameters**: - `rect` (Rect) - The normalized coordinates for the frame. - **Returns**: void. - **`webView.Show()`** - **Purpose**: Display the web view on the screen. - **Returns**: void. - **`webView.Hide()`** - **Purpose**: Hide the web view from the screen. - **Returns**: void. - **`webView.Reload()`** - **Purpose**: Reload the current web page. - **Returns**: void. - **`webView.StopLoading()`** - **Purpose**: Cancel the current page load operation. - **Returns**: void. - **`webView.ClearCache()`** - **Purpose**: Clear all cached web content for the web view. - **Returns**: void. ### Initialization - **`WebView.Initialize(globalSettings)`** - **Purpose**: Initialize the WebView system with global settings. Should be called once before creating instances. - **Parameters**: - `globalSettings` (WebViewUnitySettings) - Global settings for WebView initialization. - **Returns**: void. ``` -------------------------------- ### Initiate Product Purchase Flow (C#) Source: https://assetstore.essentialkit.voxelbusters.com/features/billing-services/usage Initiates the purchase process for a given product after verifying that payments are enabled on the device. It retrieves the product details and calls the `BuyProduct` method. This function logs warnings if payments are not available or if the product is not found. It requires a product ID as input. ```csharp public void OnBuyButtonClicked(string productId) { if (!BillingServices.CanMakePayments()) { Debug.LogWarning("Purchases not available"); return; } var product = BillingServices.GetProductWithId(productId); if (product == null) { Debug.LogError($"Product {productId} not found"); return; } BillingServices.BuyProduct(product); Debug.Log("Purchase initiated..."); } ``` -------------------------------- ### C# Manual Deep Link Services Initialization Source: https://assetstore.essentialkit.voxelbusters.com/features/deep-link-services/usage This C# code demonstrates how to manually initialize Deep Link Services in Unity, providing runtime configuration options. It involves loading deep link definitions from a server, setting up platform-specific properties, and initializing the service. This approach is for advanced scenarios such as dynamic configurations or white-label apps. ```csharp void Awake() { var iosLinks = LoadIosDefinitionsFromServer(); // DeepLinkDefinition[] var androidLinks = LoadAndroidDefinitionsFromServer(); // DeepLinkDefinition[] var settings = new DeepLinkServicesUnitySettings( iosProperties: new DeepLinkServicesUnitySettings.IosPlatformProperties( customSchemeUrls: iosLinks), androidProperties: new DeepLinkServicesUnitySettings.AndroidPlatformProperties( universalLinks: androidLinks)); DeepLinkServices.Initialize(settings); // Set delegate if needed DeepLinkServices.Delegate = new GameDeepLinkDelegate(); } ``` -------------------------------- ### Manage Application Icon Badge Number Source: https://assetstore.essentialkit.voxelbusters.com/features/notification-services/usage Demonstrates how to set and clear the badge number displayed on the application icon. This is typically used to indicate the number of unread notifications or pending items. It also shows an example of clearing the badge when the application gains focus. ```csharp // Set badge number NotificationServices.SetApplicationIconBadgeNumber(5); // Clear badge NotificationServices.SetApplicationIconBadgeNumber(0); ``` ```csharp // Clear badge when app gains focus void OnApplicationFocus(bool hasFocus) { if (hasFocus) { NotificationServices.SetApplicationIconBadgeNumber(0); } } ``` ```csharp // Increment badge when scheduling notification var notification = NotificationBuilder.CreateNotification("daily_reward") .SetTitle("Daily Reward Available!") .SetBadge(1) // Show badge count in notification .Create(); ``` -------------------------------- ### Handle Platform-Specific Code in C# (Unity) Source: https://assetstore.essentialkit.voxelbusters.com/features/game-services/notes/migration-guide-from-google-play-games-plugin-for-unity-to-essential-kit-game-services Demonstrates platform-specific code handling using preprocessor directives for iOS and Android. It illustrates how to include platform-specific logic while maintaining a single codebase. This example logs platform information. ```csharp #if UNITY_IOS // iOS-specific behavior (if needed) Debug.Log("Running on iOS with Game Center integration"); #elif UNITY_ANDROID // Android-specific behavior (if needed) Debug.Log("Running on Android with Play Games Services"); #endif ``` -------------------------------- ### Redeem Offers for Purchases in C# Source: https://assetstore.essentialkit.voxelbusters.com/features/billing-services/usage This C# snippet demonstrates how to create offer redemption details and use them when purchasing a product. It includes methods for setting platform-specific offer properties and building the purchase options with the redeemed offer. Requires `BillingServices` and related classes. ```csharp BillingProductOfferRedeemDetails GetOfferDetails(string offerId) { if (string.IsNullOrEmpty(offerId)) return null; var builder = new BillingProductOfferRedeemDetails.Builder(); builder.SetAndroidPlatformProperties(offerId); builder.SetIosPlatformProperties(offerId, keyId: null, nonce: null, signature: null, timestamp: 0); return builder.Build(); } void PurchaseWithOffer(string productId, string offerId) { var product = BillingServices.GetProductWithId(productId); var offerDetails = GetOfferDetails(offerId); var options = new BuyProductOptions.Builder() .SetOfferRedeemDetails(offerDetails) .Build(); BillingServices.BuyProduct(product, options); } ``` -------------------------------- ### C# Score Reporting Migration Source: https://assetstore.essentialkit.voxelbusters.com/features/game-services/notes/migration-guide-from-google-play-games-plugin-for-unity-to-essential-kit-game-services Covers the migration of reporting player scores from Google Play Games' `Social.ReportScore` to Essential Kit's `GameServices.ReportScore`. Includes an example of using a context tag for more specific reporting in Essential Kit. ```csharp // OLD: Google Play Games score reporting Social.ReportScore(1000, "high_scores", (bool success) => { Debug.Log($"Score reported: {success}"); }); // NEW: Essential Kit score reporting GameServices.ReportScore("high_scores", 1000, (error) => { if (error == null) { Debug.Log("Score reported successfully"); } else { Debug.LogError($"Score report error: {error.Description}"); } }); // NEW: Score reporting with context tag GameServices.ReportScore("high_scores", 1000, (error) => { // Handle callback }, tag: "level_1"); ``` -------------------------------- ### Schedule Tournament with DatePicker - C# Source: https://assetstore.essentialkit.voxelbusters.com/features/native-ui/usage This C# example utilizes the DatePicker API to allow users to schedule a tournament. It demonstrates setting minimum and maximum selectable dates, an initial date, and handling the user's selection via a callback. ```csharp public void ScheduleTournament() { DatePicker datePicker = DatePicker.CreateInstance(DatePickerMode.DateAndTime); // Tournament must be at least 24 hours in future datePicker.SetMinimumDate(DateTime.Now.AddDays(1)); datePicker.SetMaximumDate(DateTime.Now.AddMonths(1)); datePicker.SetInitialDate(DateTime.Now.AddDays(7)); datePicker.SetOnCloseCallback((result) => { if (result.ResultCode == DatePickerResultCode.Done) { ShowConfirmation(result.Date); } }); datePicker.Show(); } void ShowConfirmation(DateTime tournamentDate) { AlertDialog dialog = AlertDialog.CreateInstance(); dialog.Title = "Confirm Tournament"; dialog.Message = $"Schedule tournament for {tournamentDate:MMM dd 'at' HH:mm}?"; dialog.AddButton("Confirm", () => { Debug.Log("Tournament scheduled for: " + tournamentDate); }); dialog.AddCancelButton("Cancel", () => { }); dialog.Show(); } ``` -------------------------------- ### Check Social Share Composer Availability (C#) Source: https://assetstore.essentialkit.voxelbusters.com/features/sharing/setup This code snippet checks if specific social media composers, such as Facebook, Twitter, and WhatsApp, are available on the device using `SocialShareComposer.IsComposerAvailable()`. This is crucial for ensuring that sharing options are only presented when the corresponding social media apps are installed and configured. ```csharp if (SocialShareComposer.IsComposerAvailable(SocialShareComposerType.Facebook)) { Debug.Log("Facebook sharing available"); } if (SocialShareComposer.IsComposerAvailable(SocialShareComposerType.Twitter)) { Debug.Log("Twitter sharing available"); } if (SocialShareComposer.IsComposerAvailable(SocialShareComposerType.WhatsApp)) { Debug.Log("WhatsApp sharing available"); } ``` -------------------------------- ### Show Configurable Text Input Dialog in C# Source: https://assetstore.essentialkit.voxelbusters.com/features/native-ui/usage Demonstrates how to create an alert dialog with text input fields, allowing customization of placeholder text and secure entry for password fields. ```csharp public void ShowCustomTextInput() { AlertDialog dialog = AlertDialog.CreateInstance(); dialog.Title = "Login"; dialog.Message = "Enter your credentials:"; // Username field with placeholder var usernameOptions = new TextInputFieldOptions.Builder() .SetPlaceholder("Username") .Build(); dialog.AddTextInputField(usernameOptions); // Password field (secure entry) var passwordOptions = new TextInputFieldOptions.Builder() .SetPlaceholder("Password") .SetSecureTextEntry(true) .Build(); dialog.AddTextInputField(passwordOptions); dialog.AddButton("Login", (inputTexts) => { string username = inputTexts[0]; string password = inputTexts[1]; Debug.Log($"Login attempt: {username}"); }); dialog.AddCancelButton("Cancel", (inputTexts) => { }); dialog.Show(); } ``` -------------------------------- ### C# Essential Kit Add Friend Feature Source: https://assetstore.essentialkit.voxelbusters.com/features/game-services/notes/migration-guide-from-google-play-games-plugin-for-unity-to-essential-kit-game-services Introduces a new feature in Essential Kit for adding friends by player ID. This functionality was not directly covered in the provided Google Play Games examples. It demonstrates the `GameServices.AddFriend` method and its callback for success or error. ```csharp // NEW: Essential Kit specific feature - Add friend GameServices.AddFriend("player_id_to_add", (success, error) => { if (error == null && success) { Debug.Log("Friend request sent successfully"); } }); ``` -------------------------------- ### Configure Dynamic Host Address at Runtime Source: https://assetstore.essentialkit.voxelbusters.com/features/network-services/faq Demonstrates how to dynamically set a server's host address at runtime using manual initialization. This is useful for switching between different server environments (dev, staging, production) or for region-specific deployments. ```csharp void ConfigureForRegion(string serverURL) { var settings = new NetworkServicesUnitySettings( isEnabled: true, hostAddress: new Address { IPv4 = serverURL }, autoStartNotifier: false); NetworkServices.Initialize(settings); NetworkServices.StartNotifier(); } ``` -------------------------------- ### Subscribe to Game Services Events in C# (Essential Kit) Source: https://assetstore.essentialkit.voxelbusters.com/features/game-services/notes/migration-guide-from-google-play-games-plugin-for-unity-to-essential-kit-game-services Shows how to subscribe and unsubscribe to game services events, specifically focusing on authentication status changes. This is typically done in the Start and OnDestroy methods to manage event listeners effectively, preventing memory leaks. ```csharp // NEW: Essential Kit event subscriptions (in Start or Awake) private void Start() { // Subscribe to authentication status changes GameServices.OnAuthStatusChange += OnAuthStatusChange; } private void OnDestroy() { // Unsubscribe to prevent memory leaks GameServices.OnAuthStatusChange -= OnAuthStatusChange; } ``` -------------------------------- ### Adding Multiple Shortcuts Source: https://assetstore.essentialkit.voxelbusters.com/features/app-shortcuts/usage Demonstrates how to add multiple application shortcuts in sequence using the AppShortcutItem.Builder. ```APIDOC ## POST /api/shortcuts ### Description Add multiple shortcuts to the app icon menu. They are displayed in the order they are added, though the exact order may be platform-dependent. ### Method POST ### Endpoint /api/shortcuts ### Parameters #### Request Body - **shortcuts** (array) - Required - An array of `AppShortcutItem` objects to add. ### Request Example ```json { "shortcuts": [ { "id": "quick-match", "title": "Quick Match", "subtitle": "Jump into a quick game", "iconFileName": "quick-match.png" }, { "id": "daily-challenge", "title": "Daily Challenge", "subtitle": "Complete today's challenge", "iconFileName": "challenge.png" } ] } ``` ### Response #### Success Response (200) - **message** (string) - Success message indicating shortcuts were added. #### Response Example ```json { "message": "Shortcuts added successfully." } ``` ``` -------------------------------- ### Opening App Store Pages Source: https://assetstore.essentialkit.voxelbusters.com/features/utilities/usage This section details how to open your app's store page or specific app store pages using various methods. ```APIDOC ## POST /api/utilities/openAppStorePage ### Description Opens the current app's store page using the configured app store ID from Essential Kit Settings. This is useful for prompting users to leave reviews. ### Method POST ### Endpoint /api/utilities/openAppStorePage ### Parameters #### Request Body - **iosId** (string) - Optional - The iOS App Store ID. - **androidId** (string) - Optional - The Android package name. ### Request Example ```json { "iosId": "1234567890", "androidId": "com.company.appname" } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the operation. #### Response Example ```json { "status": "App store page opened successfully" } ``` ## POST /api/utilities/openAppStorePage/{appId} ### Description Opens a specific app store page using a string identifier. This can be a numeric App Store ID for iOS or a package name for Android. ### Method POST ### Endpoint /api/utilities/openAppStorePage/{appId} ### Parameters #### Path Parameters - **appId** (string) - Required - The platform-specific app identifier (iOS numeric ID or Android package name). ### Request Example ```json { "appId": "1234567890" } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the operation. #### Response Example ```json { "status": "App store page opened successfully" } ``` ``` -------------------------------- ### Start Network Monitoring Source: https://assetstore.essentialkit.voxelbusters.com/features/network-services/faq Ensures network monitoring is started by calling `NetworkServices.StartNotifier()`. It checks if monitoring is already active to avoid redundant calls. This is typically called in the `Start()` method or when the component is enabled. ```csharp void Start() { if (!NetworkServices.IsNotifierActive) { NetworkServices.StartNotifier(); Debug.Log("Network monitoring started"); } } ``` -------------------------------- ### Runtime Initialization of App Shortcuts - C# Source: https://assetstore.essentialkit.voxelbusters.com/features/app-shortcuts/usage Shows how to manually initialize App Shortcuts at runtime, overriding default inspector settings. This is necessary for dynamically configuring shortcut icons based on external data like server responses or user preferences. It requires creating an `AppShortcutsUnitySettings` instance and calling `AppShortcuts.Initialize()`. This method should be called only once, ideally during application startup. ```csharp void Awake() { var settings = new AppShortcutsUnitySettings( isEnabled: true, icons: runtimeIconList); // Populate from Addressables, remote configs, etc. AppShortcuts.Initialize(settings); } ``` -------------------------------- ### Recover Camera Permission Flow (C#) Source: https://assetstore.essentialkit.voxelbusters.com/features/utilities/usage Guides users through re-granting camera permission by checking the current status and opening application settings if denied. It displays an explanatory dialog with an option to proceed to settings. ```csharp public void RecoverCameraPermission() { // Check permission status first var status = MediaServices.GetCameraAccessStatus(); if (status == CameraAccessStatus.Denied) { ShowPermissionExplanation(() => { Utilities.OpenApplicationSettings(); }); } } void ShowPermissionExplanation(System.Action onOpenSettings) { AlertDialog dialog = AlertDialog.CreateInstance(); dialog.Title = "Camera Access Needed"; dialog.Message = "To scan QR codes, enable Camera in Settings > Permissions."; dialog.AddButton("Open Settings", () => onOpenSettings?.Invoke()); dialog.AddCancelButton("Not Now", () => { }); dialog.Show(); } ```