本節提供詳細的導入指南,說明如何使用 Google Play 遊戲電腦版 Unity SDK 支援的核心模組:
初始化
您必須先初始化 SDK,才能使用任何其他功能。這個程序會在 Unity 遊戲和 Google Play 遊戲電腦版執行階段之間建立連線。
命名空間: PlayPcSdkManaged.Initialization
進入點: GooglePlayInitialization
導入
您必須從 PlayPcSdkFactory 擷取 Unity 專屬的回呼處理常式,然後傳遞至初始化方法。為確保穩定性,建議您將初始化邏輯包裝在安全非同步執行器中,處理潛在例外狀況並防止重複初始化。
using UnityEngine; using System; using System.Threading.Tasks; // Import the SDK namespaces using PlayPcSdkManaged.Initialization; using PlayPcSdkManaged.Unity; public class GooglePlayPCSDKInit : MonoBehaviour { // Prevent double-initialization if this script is reloaded private static bool _isInitialized = false; private void Start() { // Use the "Safe Runner" pattern to fire the async method _ = InitializeSdkAsync(); } private async Task InitializeSdkAsync() { if (_isInitialized) { Debug.LogWarning("SDK is already initialized. Skipping."); return; } try { Debug.Log("Initializing Google Play PC SDK..."); // 1. Get the Unity-specific initialization handler from the factory var initHandler = PlayPcSdkFactory.InitializationHandler; // 2. Call InitializeAsync to start the connection var result = await GooglePlayInitialization.InitializeAsync(initHandler); // 3. Check the result if (result.IsOk) { _isInitialized = true; Debug.Log("SDK Initialized Successfully! "); // You can now create BillingClient or IntegrityClient instances } else { Debug.LogError($"Initialization Failed! "); Debug.LogError($"Error Code: {result.Code}"); Debug.LogError($"Message: {result.ErrorMessage}"); } } catch (Exception ex) { // Catch unexpected crashes or task failures Debug.LogError($"Exception during initialization: {ex.Message}"); Debug.LogException(ex); } } }
錯誤處理參考資料
SDK 會使用 Result 物件處理所有預期的 API 結果。您應檢查
Result.Code,以處理網路錯誤或使用者取消等情境。
注意:雖然 SDK API 本身不會針對邏輯錯誤擲回例外狀況,但我們仍建議將頂層 async 方法包裝在 try-catch 區塊中。這樣可確保 Unity 控制台會正確記錄非預期的執行階段錯誤 (例如您自己程式碼中的空值參照或工作排程失敗)。