本部分针对 Google Play Games PC SDK for Unity 支持的核心模块提供了详细的实现指南:
初始化
您必须先初始化 SDK,然后才能尝试使用任何其他功能。此过程会在您的 Unity 游戏与 Google Play Games on PC 运行时之间建立连接。
命名空间: 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 会针对所有预期 API 结果使用 Result 对象。您应检查 Result.Code 以处理网络错误或用户取消等情况。
注意:虽然 SDK API 本身不会针对逻辑错误抛出异常,但我们仍建议将顶级 async 方法封装在 try-catch 块中。这样可确保在 Unity 控制台中正确记录意外的运行时错误(例如您自己的代码中的 null 引用或任务调度失败)。