适用于Unity的SDK / 在应用程序侧集成SDK
 返回文档

适用于Unity的SDK

  • 集成指南

  • 演示项目

  • 身份认证

  • 目录

  • 订阅

  • 促销活动

  • 商品购买

  • 玩家物品库

  • 用户帐户和属性

  • 应用程序编译版本指南

  • 故障排除


  • 在应用程序侧集成SDK

    1. 设计应用程序的登录系统、游戏内商店及其他页面的界面。
    2. 使用SDK方法在应用程序中实现用户认证、商店显示、购买及其他逻辑。

    注:
    您可以按照Unity说明中的信息创建自己的解决方案,也可以将演示场景用作模板。要根据自己的应用程序调整演示场景UI,请使用UI生成器

    要使用基础SDK功能,请按照以下分步教程进行操作:

    可在SDK的Assets/Xsolla/Samples目录下找到使用的脚本。

    通过用户名/邮箱和密码进行用户登录

    本说明解释如何使用SDK方法实现以下内容:

    • 用户注册
    • 重新发送注册验证邮件请求
    • 用户登录
    • 用户密码重置

    您可以使用用户名或邮箱地址来认证用户身份。以下示例中,我们使用用户的用户名来进行认证,使用邮箱地址来进行注册验证及重置密码。

    注:
    如果您在网站上(例如Web商店)使用了登录管理器小组件,请确保该网站与您的应用程序实现相同的用户认证方法。小组件默认使用邮箱地址进行认证。如要设置通过用户名进行用户登录,请联系您的客户成功经理或发送邮件至csm@xsolla.com

    示例中的逻辑与界面比您在应用程序中的简单得多。演示项目提供了一种可能的认证系统实现方案。

    实现用户注册

    本教程介绍以下逻辑的实现:

    创建页面界面

    为注册页面创建一个场景并在页面上添加以下元素:

    • 用户名字段
    • 用户邮箱地址字段
    • 用户密码字段
    • 注册按钮

    下图为页面结构的示例。

    创建页面控制器

    1. 创建一个继承自MonoBehaviour基类的脚本RegistrationPage
    2. 声明网页界面元素的变量并Inspector面板中设置它们的值
    3. 添加逻辑来处理对注册按钮的点击,如脚本示例中所示。

    注:

    在脚本示例中,OnSuccessOnError方法调用标准Debug.Log方法。发生错误时,错误代码和描述在error参数中传递。

    您还可以添加其他动作,例如打开一个包含重新发送注册邮件请求的页面或在注册成功时打开一个登录页面。

    注册页面的脚本示例:

    Copy
    Full screen
    Small screen

    using UnityEngine;
    using UnityEngine.UI;
    using Xsolla.Auth;
    using Xsolla.Core;
    
    namespace Xsolla.Samples.Authorization
    {
        public class RegistrationPage : MonoBehaviour
        {
            // Declaration of variables for UI elements
         public InputField UsernameInput;
            public InputField EmailInputField;
            public InputField PasswordInputField;
            public Button RegisterButton;
    
            private void Start()
            {
                // Handling the button click
             RegisterButton.onClick.AddListener(() =>
                {
                    // Get the username, email and password from input fields
                 var username = UsernameInput.text;
                    var email = EmailInputField.text;
                    var password = PasswordInputField.text;
    
                    // Call the user registration method
                 // Pass credentials and callback functions for success and error cases
                 XsollaAuth.Register(username, password, email, OnSuccess, OnError);
                });
            }
    
            private void OnSuccess(LoginLink loginLink)
            {
                Debug.Log("Registration successful");
                // Add actions taken in case of success
         }
    
            private void OnError(Error error)
            {
                Debug.LogError($"Registration failed. Error: {error.errorMessage}");
                // Add actions taken in case of error
         }
        }
    }
    

    设置注册验证邮件

    成功注册后,用户将在指定邮箱中收到一封注册验证邮件。您可以在发布商帐户中自定义发送给用户的邮件

    如果您开发的是Android应用程序,请设置深度链接以在用户验证注册后将用户返回到应用程序。

    注:
    如果您安全性标准允许,可禁用通过邮箱地址进行注册验证。请联系您的客户成功经理进行禁用或发送邮件至csm@xsolla.com与我们联系。

    实现重新发送注册验证邮件请求

    本教程介绍以下逻辑的实现:

    创建页面界面

    为包含重新发送验证邮件请求的页面创建一个场景并在页面上添加以下元素:

    • 用户名/邮箱字段
    • 重新发送邮件按钮

    下图为页面结构的示例。

    创建页面控制器

    1. 创建一个继承自MonoBehaviour基类的脚本ResendConfirmationEmail
    2. 声明网页界面元素的变量并Inspector面板中设置它们的值
    3. 添加逻辑来处理对重新发送邮件按钮的点击,如脚本示例中所示。

    重新发送邮件页面的脚本示例:

    Copy
    Full screen
    Small screen

    using UnityEngine;
    using UnityEngine.UI;
    using Xsolla.Auth;
    using Xsolla.Core;
    
    namespace Xsolla.Samples.Authorization
    {
        public class ResendConfirmationEmailPage : MonoBehaviour
        {
            // Declaration of variables for UI elements
         public InputField UsernameInput;
            public Button ResendEmailButton;
    
            private void Start()
            {
                // Handling the button click
             ResendEmailButton.onClick.AddListener(() =>
                {
                    // Get the username from the input field
                 var username = UsernameInput.text;
    
                    // Call the resend confirmation email method
                 // Pass the username and callback functions for success and error cases
                 XsollaAuth.ResendConfirmationLink(username, OnSuccess, OnError);
                });
            }
    
            private void OnSuccess()
            {
                Debug.Log("Resend confirmation email successful");
                // Add actions taken in case of success
         }
    
            private void OnError(Error error)
            {
                Debug.LogError($"Resend confirmation email failed. Error: {error.errorMessage}");
                // Add actions taken in case of error
         }
        }
    }
    

    如果请求成功,用户将在注册时指定的邮箱中收到一封注册验证邮件。

    实现用户登录

    本教程介绍以下逻辑的实现:

    创建页面界面

    为登录页面创建一个场景并在页面上添加以下元素:

    • 用户名字段
    • 密码字段
    • 记住我复选框
    • 登录按钮

    下图为页面结构的示例。

    创建页面控制器

    1. 创建一个继承自MonoBehaviour基类的脚本AutorizationPage
    2. 声明网页界面元素的变量并Inspector面板中设置它们的值
    3. 添加逻辑来处理对登录按钮的点击,如脚本示例中所示。

    登录页面的脚本示例:

    Copy
    Full screen
    Small screen

    using UnityEngine;
    using UnityEngine.UI;
    using Xsolla.Auth;
    using Xsolla.Core;
    
    namespace Xsolla.Samples.Authorization
    {
        public class AuthorizationPage : MonoBehaviour
        {
            // Declaration of variables for UI elements
         public InputField UsernameInput;
            public InputField PasswordInputField;
            public Button SignInButton;
    
            private void Start()
            {
                // Handling the button click
             SignInButton.onClick.AddListener(() =>
                {
                    // Get the username and password from input fields
                 var username = UsernameInput.text;
                    var password = PasswordInputField.text;
    
                    // Call the user authorization method
                 // Pass credentials and callback functions for success and error cases
                 XsollaAuth.SignIn(username, password, OnSuccess, OnError);
                });
            }
    
            private void OnSuccess()
            {
                Debug.Log("Authorization successful");
                // Add actions taken in case of success
         }
    
            private void OnError(Error error)
            {
                Debug.LogError($"Authorization failed. Error: {error.errorMessage}");
                // Add actions taken in case of error
         }
        }
    }
    

    实现密码重置

    本教程介绍以下逻辑的实现:

    创建页面界面

    为密码重置页面创建一个场景并在页面上添加以下元素:

    • 用户名/邮箱字段
    • 密码重置按钮

    下图为页面结构的示例。

    创建页面控制器

    1. 创建一个继承自MonoBehaviour基类的脚本ResetPasswordPage
    2. 声明网页界面元素的变量并Inspector面板中设置它们的值
    3. 添加逻辑来处理对密码重置按钮的点击,如脚本示例中所示。

    密码重置页面的脚本示例:

    Copy
    Full screen
    Small screen

    using UnityEngine;
    using UnityEngine.UI;
    using Xsolla.Auth;
    using Xsolla.Core;
    
    namespace Xsolla.Samples.Authorization
    {
        public class ResetPasswordPage : MonoBehaviour
        {
            // Declaration of variables for UI elements
         public InputField UsernameInput;
            public Button ResetPasswordButton;
    
            private void Start()
            {
                // Handling the button click
             ResetPasswordButton.onClick.AddListener(() =>
                {
                    // Get the username from the input field
                 var username = UsernameInput.text;
    
                    // Call the password reset method
                 // Pass the username and callback functions for success and error cases
                 XsollaAuth.ResetPassword(username, OnSuccess, OnError);
                });
            }
    
            private void OnSuccess()
            {
                Debug.Log("Password reset successful");
                // Add actions taken in case of success
         }
    
            private void OnError(Error error)
            {
                Debug.LogError($"Password reset failed. Error: {error.errorMessage}");
                // Add actions taken in case of error
         }
        }
    }
    

    成功发出密码重置请求后,用户将收到一封包含密码重置链接的邮件。在发布商帐户 > 登录管理器项目 > 安全性 > OAuth 2.0 > OAuth 2.0重定向URI中,您可以配置用户成功完成认证、邮箱验证或密码重置后将其重定向到的URL地址或路径。

    社交网络帐户登录

    本指南说明如何使用SDK方法实现通过社交网络帐户进行用户注册和登录。

    通过用户名/邮箱地址和密码进行用户认证不同,您无需实现单独的用户注册逻辑。如果用户的首次登录是通过社交网络进行,将自动创建一个帐户。

    如果您在应用程序中将社交网络登录设置为一种备选认证方法,则在满足下列条件的情况下,社交网络帐户将自动与现有用户帐户关联:

    • 已使用用户名/邮箱地址和密码注册的用户通过社交网络帐户登录您的应用程序。
    • 社交网络返回一个邮箱地址。
    • 社交网络帐户中的用户邮箱地址与注册您的应用程序时使用的邮箱地址一致。

    注:
    您可以实现社交网络帐户的手动关联。您可以在应用程序中添加一个让用户将社交网络帐户与帐户关联的页面。在页面控制器中,请使用LinkSocialProvider SDK方法。

    本教程介绍以下逻辑的实现:

    示例展示了如何设置通过Facebook帐户进行用户登录。您可以用相同的方法设置其他社交网络。

    示例中的逻辑与界面比您在应用程序中的简单得多。演示项目提供了一种可能的认证系统实现方案。

    创建页面界面

    为登录页创建一个场景并在其中添加社交网络登录按钮。下图为页面结构的示例。

    创建页面控制器

    1. 创建一个继承自MonoBehaviour基类的脚本SocialAuthorizationPage
    2. 声明应用程序登录页面界面元素的变量并Inspector面板中设置它们的值
    3. 添加逻辑来处理对登录按钮的点击,如脚本示例中所示。

    注:

    在脚本示例中,OnSuccessOnError方法调用标准Debug.Log方法。您还可以添加其他动作。

    发生错误时,错误代码和描述在error参数中传递。

    登录页面的脚本示例:

    Copy
    Full screen
    Small screen

    using UnityEngine;
    using UnityEngine.UI;
    using Xsolla.Auth;
    using Xsolla.Core;
    
    namespace Xsolla.Samples.Authorization
    {
        public class SocialAuthorizationPage : MonoBehaviour
        {
            // Declaration of variables for SocialProvider and signIn button
         public SocialProvider SocialProvider = SocialProvider.Facebook;
            public Button SignInButton;
    
            private void Start()
            {
                // Handling the button click
             SignInButton.onClick.AddListener(() =>
                {
                    // Call the social authorization method
                 // Pass the social network provider and callback functions for success, error and cancel cases
                 XsollaAuth.AuthViaSocialNetwork(SocialProvider, OnSuccess, OnError, OnCancel);
                });
            }
    
            private void OnSuccess()
            {
                Debug.Log("Social authorization successful");
                // Add actions taken in case of success
         }
    
            private void OnError(Error error)
            {
                Debug.LogError($"Social authorization failed. Error: {error.errorMessage}");
                // Add actions taken in case of error
         }
    
            private void OnCancel()
            {
                Debug.Log("Social authorization cancelled by user.");
                // Add actions taken in case the user canceles authorization
         }
        }
    }
    

    显示商品目录

    本教程介绍如何使用SDK方法在游戏内商店中显示以下商品:

    • 虚拟物品
    • 虚拟物品组
    • 捆绑包
    • 虚拟货币套餐

    开始之前,请在发布商帐户中配置商品:

    1. 配置虚拟物品和虚拟物品组
    2. 配置虚拟货币套餐
    3. 配置捆绑包

    本教程介绍以下逻辑的实现:

    示例中的逻辑与界面比您实际在应用程序中的要简单得多。演示项目提供了一种可能的游戏内商店商品目录实现方案。

    注:

    目录中的每个商品示例显示以下内容:

    • 商品名称
    • 商品描述
    • 商品价格
    • 图片

    如果游戏内商店中还存储了其他信息,也可以显示那些信息。

    实现虚拟物品的显示

    创建商品小组件

    1. 创建一个空游戏对象。方法是前往主菜单,然后选择GameObject > Create Empty
    2. Hierarchy面板拖动一个游戏对象到Project面板,以转换预制件中创建的游戏对象。
    3. 选择一个创建的预制件,然后在Inspector面板中单击Open Prefab
    4. 将以下UI元素添加为预制件子对象并配置其视觉显示:
      • 商品背景图片
      • 商品名称
      • 商品描述
      • 商品价格
      • 商品图片

    下图为小组件结构的示例。

    创建商品小组件脚本

    1. 创建一个继承自MonoBehaviour基类的脚本VirtualItemWidget
    2. 声明商品小组件界面元素的变量并Inspector面板中设置它们的值

    小组件脚本的示例:

    Copy
    Full screen
    Small screen

    using UnityEngine;
    using UnityEngine.UI;
    
    namespace Xsolla.Samples.DisplayCatalog
    {
        public class VirtualItemWidget : MonoBehaviour
        {
            // Declaration of variables for UI elements
         public Text NameText;
            public Text DescriptionText;
            public Text PriceText;
            public Image IconImage;
        }
    }
    

    创建显示商品列表的页面

    1. 在场景上创建一个空游戏对象。方法是前往主菜单,然后选择GameObject > Create Empty
    2. 将以下UI元素添加为预制件子对象并配置其视觉显示:
      • 页面背景图片
      • 商品小组件显示区域

    下图为页面结构的示例。

    创建页面控制器

    1. 创建继承自MonoBehaviour基类的脚本VirtualItemsPage
    2. 声明以下变量:
      • WidgetsContainer — 小组件的容器
      • WidgetPrefab — 商品小组件预制件

    1. 将脚本与页面游戏对象关联:
      1. Hierarchy面板中选择一个对象。
      2. Inspector面板中,单击Add Component,然后选择一个VirtualItemsPage脚本。
    2. Inspector面板中设置变量的值。

    1. 添加登录逻辑和获取商品列表的逻辑,如脚本示例中所示。

    注:

    在登录脚本示例中我们使用的是演示帐户的凭证(用户名:xsolla,密码:xsolla)。

    脚本示例不包含按页显示目录中商品(分页)的实现。请使用GetCatalog SDK方法的offsetlimit参数来实现分页。每页最大商品数为50。如目录中的商品数超过50,则需要分页。

    页面控制器脚本示例:

    Copy
    Full screen
    Small screen

    using System.Linq;
    using UnityEngine;
    using Xsolla.Auth;
    using Xsolla.Catalog;
    using Xsolla.Core;
    
    namespace Xsolla.Samples.DisplayCatalog
    {
        public class VirtualItemsPage : MonoBehaviour
        {
            // Declaration of variables for widget's container and prefab
         public Transform WidgetsContainer;
            public GameObject WidgetPrefab;
    
            private void Start()
            {
                // Starting the authentication process
             // Pass the credentials and callback functions for success and error cases
             // The credentials (username and password) are hard-coded for simplicity
             XsollaAuth.SignIn("xsolla", "xsolla", OnAuthenticationSuccess, OnError);
            }
    
            private void OnAuthenticationSuccess()
            {
                // Starting the items request from the store after successful authentication
             XsollaCatalog.GetCatalog(OnItemsRequestSuccess, OnError);
            }
    
            private void OnItemsRequestSuccess(StoreItems storeItems)
            {
                // Iterating the items collection
             foreach (var storeItem in storeItems.items)
                {
                    // Instantiating the widget prefab as child of the container
                 var widgetGo = Instantiate(WidgetPrefab, WidgetsContainer, false);
                    var widget = widgetGo.GetComponent<VirtualItemWidget>();
    
                    // Assigning the values for UI elements
                 widget.NameText.text = storeItem.name;
                    widget.DescriptionText.text = storeItem.description;
    
                    // The item can be purchased for real money or virtual currency
                 // Checking the price type and assigning the values for appropriate UI elements
                 if (storeItem.price != null)
                    {
                        var realMoneyPrice = storeItem.price;
                        widget.PriceText.text = $"{realMoneyPrice.amount} {realMoneyPrice.currency}";
                    }
                    else if (storeItem.virtual_prices != null)
                    {
                        var virtualCurrencyPrice = storeItem.virtual_prices.First(x => x.is_default);
                        widget.PriceText.text = $"{virtualCurrencyPrice.name}: {virtualCurrencyPrice.amount}";
                    }
    
                    // Loading the item image and assigning it to the UI element
                 ImageLoader.LoadSprite(storeItem.image_url, sprite => widget.IconImage.sprite = sprite);
                }
            }
    
            private void OnError(Error error)
            {
                Debug.LogError($"Error: {error.errorMessage}");
                // Add actions taken in case of error
         }
        }
    }
    

    下图为脚本的运行结果。

    实现虚拟物品组的显示

    创建商品小组件

    1. 创建一个空游戏对象。方法是前往主菜单,然后选择GameObject > Create Empty
    2. Hierarchy面板拖动一个游戏对象到Project面板,以转换预制件中创建的游戏对象。
    3. 选择一个创建的预制件,然后在Inspector面板中单击Open Prefab
    4. 将以下UI元素添加为预制件子对象并配置其视觉显示:
      • 商品背景图片
      • 商品名称
      • 商品描述
      • 商品价格
      • 商品图片

    下图为小组件结构的示例。

    创建商品小组件脚本

    1. 创建一个继承自MonoBehaviour基类的脚本VirtualItemWidget
    2. 声明商品小组件界面元素的变量并Inspector面板中设置它们的值

    小组件脚本的示例:

    Copy
    Full screen
    Small screen

    using UnityEngine;
    using UnityEngine.UI;
    
    namespace Xsolla.Samples.DisplayCatalog
    {
        public class VirtualItemWidget : MonoBehaviour
        {
            // Declaration of variables for UI elements
         public Text NameText;
            public Text DescriptionText;
            public Text PriceText;
            public Image IconImage;
        }
    }
    

    创建打开商品组按钮的小组件

    1. 创建一个空游戏对象。方法是前往主菜单,然后选择GameObject > Create Empty
    2. Hierarchy面板拖动一个游戏对象到Project面板,以转换预制件中创建的游戏对象。
    3. 选择一个创建的预制件,然后在Inspector面板中单击Open Prefab
    4. 将允许商品组显示的按钮添加为预制件的子对象并配置其视觉显示。

    下图为小组件结构的示例。

    创建打开商品组按钮的脚本

    1. 创建继承自MonoBehaviour基类的VirtualItemGroupButton脚本。
    2. 声明打开商品组按钮的变量,并在Inspector面板中设置变量的值。
    3. 向预制件的根对象添加一个脚本:
      1. Hierarchy面板中选择一个对象。
      2. Inspector面板中,单击Add Component,然后选择一个VirtualItemGroupButton脚本。

    小组件脚本的示例:

    Copy
    Full screen
    Small screen

    using UnityEngine;
    using UnityEngine.UI;
    
    namespace Xsolla.Samples.DisplayCatalog
    {
        public class VirtualItemGroupButton : MonoBehaviour
        {
            // Declaration of variables for UI elements
         public Text NameText;
            public Button Button;
        }
    }
    

    创建显示商品列表的页面

    1. 在场景上创建一个空游戏对象。方法是前往主菜单,然后选择GameObject > Create Empty
    2. 将以下UI元素添加为预制件子对象并配置其视觉显示:
      • 页面背景图片
      • 商品组按钮显示区域
      • 商品小组件显示区域

    下图为页面结构的示例。

    创建页面控制器

    1. 创建继承自MonoBehaviour基类的VirtualItemsByGroupsPage脚本。
    2. 声明以下变量:
      • GroupButtonsContainer — 组按钮的容器
      • GroupButtonPrefab — 按钮预制件
      • ItemWidgetsContainer — 商品小组件容器
      • WidgetPrefab — 商品小组件预制件

    1. 将脚本附加至页面游戏对象:
      1. Hierarchy面板中选择一个对象。
      2. Inspector面板中,单击Add Component,然后选择一个VirtualItemsByGroupsPage脚本。
    2. Inspector面板中设置变量的值。
    3. 添加登录逻辑和获取商品列表的逻辑,如脚本示例中所示。

    注:

    在登录脚本示例中我们使用的是演示帐户的凭证(用户名:xsolla,密码:xsolla)。

    脚本示例不包含按页显示目录中商品(分页)的实现。请使用GetCatalog SDK方法的offsetlimit参数来实现分页。每页最大商品数为50。如目录中的商品数超过50,则需要分页。

    页面控制器脚本示例:

    Copy
    Full screen
    Small screen

    using System.Collections.Generic;
    using System.Linq;
    using UnityEngine;
    using Xsolla.Auth;
    using Xsolla.Catalog;
    using Xsolla.Core;
    
    namespace Xsolla.Samples.DisplayCatalog
    {
        public class VirtualItemsByGroupsPage : MonoBehaviour
        {
            // Declaration of variables for widget's container and prefab
         public Transform GroupButtonsContainer;
            public GameObject GroupButtonPrefab;
            public Transform ItemWidgetsContainer;
            public GameObject ItemWidgetPrefab;
    
            private void Start()
            {
                // Starting the authentication process
             // Pass the credentials and callback functions for success and error cases
             // The credentials (username and password) are hard-coded for simplicity
             XsollaAuth.SignIn("xsolla", "xsolla", OnAuthenticationSuccess, OnError);
            }
    
            private void OnAuthenticationSuccess()
            {
                // Starting the items request from the store after successful authentication
             // Pass the callback functions for success and error cases
             XsollaCatalog.GetCatalog(OnItemsRequestSuccess, OnError);
            }
    
            private void OnItemsRequestSuccess(StoreItems storeItems)
            {
                // Selecting the group’s name from items and order them alphabetically
             var groupNames = storeItems.items
                    .SelectMany(x => x.groups)
                    .GroupBy(x => x.name)
                    .Select(x => x.First())
                    .OrderBy(x => x.name)
                    .Select(x => x.name)
                    .ToList();
    
                // Add group name for catalog category with all items regardless of group affiliation
             groupNames.Insert(0, "All");
    
                // Iterating the group names collection
             foreach (var groupName in groupNames)
                {
                    // Instantiating the button prefab as child of the container
                 var buttonGo = Instantiate(GroupButtonPrefab, GroupButtonsContainer, false);
                    var groupButton = buttonGo.GetComponent<VirtualItemGroupButton>();
    
                    // Assigning the values for UI elements
                 groupButton.NameText.text = groupName;
    
                    // Adding listener for button click event
                 groupButton.Button.onClick.AddListener(() => OnGroupSelected(groupName, storeItems));
                }
    
                // Calling method for redraw page
             OnGroupSelected("All", storeItems);
            }
    
            private void OnGroupSelected(string groupName, StoreItems storeItems)
            {
                // Clear container
             DeleteAllChildren(ItemWidgetsContainer);
    
                // Declaring variable for items to be displayed on the page
             IEnumerable<StoreItem> itemsForDisplay;
                if (groupName == "All")
                {
                    itemsForDisplay = storeItems.items;
                }
                else
                {
                    itemsForDisplay = storeItems.items.Where(item => item.groups.Any(group => group.name == groupName));
                }
    
                // Iterating the items collection and assigning values for appropriate UI elements
             foreach (var storeItem in itemsForDisplay)
                {
                    // Instantiating the widget prefab as child of the container
                 var widgetGo = Instantiate(ItemWidgetPrefab, ItemWidgetsContainer, false);
                    var widget = widgetGo.GetComponent<VirtualItemWidget>();
    
                    // Assigning the values for UI elements
                 widget.NameText.text = storeItem.name;
                    widget.DescriptionText.text = storeItem.description;
    
                    // The item can be purchased for real money or virtual currency
                 // Checking the price type and assigning the appropriate value for price text
                 if (storeItem.price != null)
                    {
                        var realMoneyPrice = storeItem.price;
                        widget.PriceText.text = $"{realMoneyPrice.amount} {realMoneyPrice.currency}";
                    }
                    else if (storeItem.virtual_prices != null)
                    {
                        var virtualCurrencyPrice = storeItem.virtual_prices.First(x => x.is_default);
                        widget.PriceText.text = $"{virtualCurrencyPrice.name}: {virtualCurrencyPrice.amount}";
                    }
    
                    // Loading the image for item icon and assigning it to the UI element
                 ImageLoader.LoadSprite(storeItem.image_url, sprite => widget.IconImage.sprite = sprite);
                }
            }
    
            private void OnError(Error error)
            {
                Debug.LogError($"Error: {error.errorMessage}");
                //  Add actions taken in case of error
         }
    
            // Utility method to delete all children of a container
         private static void DeleteAllChildren(Transform parent)
            {
                var childList = parent.Cast<Transform>().ToList();
                foreach (var childTransform in childList)
                {
                    Destroy(childTransform.gameObject);
                }
            }
        }
    }
    

    下图为脚本的运行结果。

    实现捆绑包的显示

    创建捆绑小组件

    1. 创建一个空游戏对象。方法是前往主菜单,然后选择GameObject > Create Empty
    2. Hierarchy面板拖动一个游戏对象到Project面板,以转换预制件中创建的游戏对象。
    3. 选择一个创建的预制件,然后在Inspector面板中单击Open Prefab
    4. 将以下UI元素添加为预制件子对象并配置其视觉显示:

      • 小组件背景图片
      • 捆绑包名称
      • 捆绑包描述
      • 捆绑包价格
      • 捆绑包内容描述(商品及其数量)
      • 捆绑包图片

    下图为小组件结构的示例。

    创建小组件脚本

    1. 创建一个继承自MonoBehaviour基类的脚本BundleWidget
    2. 声明商品小组件界面元素的变量并Inspector面板中设置它们的值

    小组件脚本的示例:

    Copy
    Full screen
    Small screen
    using UnityEngine;
    using UnityEngine.UI;
    
    namespace Xsolla.Samples.DisplayCatalog
    {
        public class BundleWidget : MonoBehaviour
        {
            // Declaration of variables for UI elements
         public Text NameText;
            public Text DescriptionText;
            public Text PriceText;
            public Text ContentText;
            public Image IconImage;
        }
    }
    

    创建显示捆绑包的页面

    1. 在场景上创建一个空游戏对象。方法是前往主菜单,然后选择GameObject > Create Empty
    2. 将以下UI元素添加为预制件子对象并配置其视觉显示:
      • 页面背景图片
      • 捆绑包小组件显示区域

    下图为页面结构的示例。

    创建页面控制器

    1. 创建继承自MonoBehaviour基类的BundlesPage脚本。
    2. 声明以下变量:
      • WidgetsContainer — 小组件的容器
      • WidgetPrefab — 捆绑包小组件预制件

    1. 将脚本附加到页面游戏对象上:
      1. Hierarchy面板中选择一个对象。
      2. Inspector面板中,单击Add Component,然后选择一个BundlesPage脚本。

    1. Inspector面板中设置变量的值。
    2. 添加登录逻辑和获取商品列表的逻辑,如脚本示例中所示。

    注:

    在登录脚本示例中我们使用的是演示帐户的凭证(用户名:xsolla,密码:xsolla)。

    脚本示例不包含按页显示目录中商品(分页)的实现。请使用GetCatalog SDK方法的offsetlimit参数来实现分页。每页最大商品数为50。如目录中的商品数超过50,则需要分页。

    页面控制器脚本示例:

    Copy
    Full screen
    Small screen

    using System.Linq;
    using UnityEngine;
    using Xsolla.Auth;
    using Xsolla.Catalog;
    using Xsolla.Core;
    
    namespace Xsolla.Samples.DisplayCatalog
    {
        public class BundlesPage : MonoBehaviour
        {
            // Declaration of variables for widget's container and prefab
         public Transform WidgetsContainer;
            public GameObject WidgetPrefab;
    
            private void Start()
            {
                // Starting the authentication process
             // Pass the credentials and callback functions for success and error cases
             // The credentials (username and password) are hard-coded for simplicity
             XsollaAuth.SignIn("xsolla", "xsolla", OnAuthenticationSuccess, OnError);
            }
    
            private void OnAuthenticationSuccess()
            {
                // Starting the bundle request from the store after successful authentication
             // Pass the callback functions for success and error cases
             XsollaCatalog.GetBundles(OnBundlesRequestSuccess, OnError);
            }
    
            private void OnBundlesRequestSuccess(BundleItems bundleItems)
            {
                // Iterating the bundles collection
             foreach (var bundleItem in bundleItems.items)
                {
                    // Instantiating the widget prefab as child of the container
                 var widgetGo = Instantiate(WidgetPrefab, WidgetsContainer, false);
                    var widget = widgetGo.GetComponent<BundleWidget>();
    
                    // Assigning the values for UI elements
                 widget.NameText.text = bundleItem.name;
                    widget.DescriptionText.text = bundleItem.description;
    
                    // Creating the string with bundle content and assigning it to the UI element
                 var bundleContent = bundleItem.content.Select(x => $"{x.name} x {x.quantity}");
                    widget.ContentText.text = string.Join("\n", bundleContent);
    
                    // The bundle can be purchased for real money or virtual currency
                 // Checking the price type and assigning the values for appropriate UI elements
                 if (bundleItem.price != null)
                    {
                        var realMoneyPrice = bundleItem.price;
                        widget.PriceText.text = $"{realMoneyPrice.amount} {realMoneyPrice.currency}";
                    }
                    else if (bundleItem.virtual_prices != null)
                    {
                        var virtualCurrencyPrice = bundleItem.virtual_prices.First(x => x.is_default);
                        widget.PriceText.text = $"{virtualCurrencyPrice.name}: {virtualCurrencyPrice.amount}";
                    }
    
                    // Loading the bundle image and assigning it to the UI element
                 ImageLoader.LoadSprite(bundleItem.image_url, sprite => widget.IconImage.sprite = sprite);
                }
            }
    
            private void OnError(Error error)
            {
                Debug.LogError($"Error: {error.errorMessage}");
                // Add actions taken in case of error
         }
        }
    }
    

    下图为脚本的运行结果。

    实现虚拟货币套餐的显示

    创建虚拟货币套餐的小组件

    1. 创建一个空游戏对象。方法是前往主菜单,然后选择GameObject > Create Empty
    2. Hierarchy面板拖动一个游戏对象到Project面板,以转换预制件中创建的游戏对象。
    3. 选择一个创建的预制件,然后在Inspector面板中单击Open Prefab
    4. 将以下UI元素添加为预制件子对象并配置其视觉显示:

      • 小组件背景图片
      • 套餐名称
      • 套餐描述
      • 套餐价格
      • 套餐图片

    下图为小组件结构的示例。

    创建小组件脚本

    1. 创建一个继承自MonoBehaviour基类的脚本VirtualCurrencyPackageWidget
    2. 声明商品小组件界面元素的变量并Inspector面板中设置它们的值

    小组件脚本的示例:

    Copy
    Full screen
    Small screen

    using UnityEngine;
    using UnityEngine.UI;
    
    namespace Xsolla.Samples.DisplayCatalog
    {
        public class VirtualCurrencyPackageWidget : MonoBehaviour
        {
            // Declaration of variables for UI elements
         public Text NameText;
            public Text DescriptionText;
            public Text PriceText;
            public Image IconImage;
        }
    }
    

    创建显示虚拟货币套餐的页面

    1. 在场景上创建一个空游戏对象。方法是前往主菜单,然后选择GameObject > Create Empty
    2. 将以下UI元素添加为预制件子对象并配置其视觉显示:
      • 页面背景图片
      • 虚拟货币套餐小组件显示区域

    下图为页面结构的示例。

    创建页面控制器

    1. 创建继承自MonoBehaviour基类的VirtualCurrencyPackagesPage脚本。
    2. 声明以下变量:
      • WidgetsContainer — 小组件的容器
      • WidgetPrefab — 虚拟货币套餐预制件

    1. 将脚本附加至页面游戏对象:
      1. Hierarchy面板中选择一个对象。
      2. Inspector面板中,单击Add Component,然后选择一个VirtualCurrencyPackagesPage脚本。
    2. Inspector面板中设置变量的值。
    3. 添加登录逻辑和获取虚拟货币套餐列表的逻辑,如脚本示例中所示。

    注:

    在登录脚本示例中我们使用的是演示帐户的凭证(用户名:xsolla,密码:xsolla)。

    脚本示例不包含按页显示目录中商品(分页)的实现。请使用GetCatalog SDK方法的offsetlimit参数来实现分页。每页最大商品数为50。如目录中的商品数超过50,则需要分页。

    页面控制器脚本示例:

    Copy
    Full screen
    Small screen

    using System.Linq;
    using UnityEngine;
    using Xsolla.Auth;
    using Xsolla.Catalog;
    using Xsolla.Core;
    
    namespace Xsolla.Samples.DisplayCatalog
    {
        public class VirtualCurrencyPackagesPage : MonoBehaviour
        {
            // Declaration of variables for widget's container and prefab
         public Transform WidgetsContainer;
            public GameObject WidgetPrefab;
    
            private void Start()
            {
                // Starting the authentication process
             // Pass the credentials and callback functions for success and error cases
             // The credentials (username and password) are hard-coded for simplicity
             XsollaAuth.SignIn("xsolla", "xsolla", OnAuthenticationSuccess, OnError);
            }
    
            private void OnAuthenticationSuccess()
            {
                // After successful authentication starting the request for packages from store
             // Pass the callback functions for success and error cases
             XsollaCatalog.GetVirtualCurrencyPackagesList(OnPackagesRequestSuccess, OnError);
            }
    
            private void OnPackagesRequestSuccess(VirtualCurrencyPackages packageItems)
            {
                // Iterating the virtual currency packages collection
             foreach (var packageItem in packageItems.items)
                {
                    // Instantiating the widget prefab as child of the container
                 var widgetGo = Instantiate(WidgetPrefab, WidgetsContainer, false);
                    var widget = widgetGo.GetComponent<VirtualCurrencyPackageWidget>();
    
                    // Assigning the values for UI elements
                 widget.NameText.text = packageItem.name;
                    widget.DescriptionText.text = packageItem.description;
    
                    // The package can be purchased for real money or virtual currency
                 // Checking the price type and assigning the values for appropriate UI elements
                 if (packageItem.price != null)
                    {
                        var realMoneyPrice = packageItem.price;
                        widget.PriceText.text = $"{realMoneyPrice.amount} {realMoneyPrice.currency}";
                    }
                    else if (packageItem.virtual_prices != null)
                    {
                        var virtualCurrencyPrice = packageItem.virtual_prices.First(x => x.is_default);
                        widget.PriceText.text = $"{virtualCurrencyPrice.name}: {virtualCurrencyPrice.amount}";
                    }
    
                    // Loading the package image and assigning it to the UI element
                 ImageLoader.LoadSprite(packageItem.image_url, sprite => widget.IconImage.sprite = sprite);
                }
            }
    
            private void OnError(Error error)
            {
                Debug.LogError($"Error: {error.errorMessage}");
                // Add actions taken in case of error
         }
        }
    }
    

    下图为脚本的运行结果。

    以真实货币计价的形式销售虚拟物品

    本节介绍如何通过SDK方法实现以真实货币形式销售虚拟物品。

    开始之前,需实现在目录中显示虚拟物品。下方示例中我们描述了如何实现虚拟物品的购买。其他商品类型的配置与此类似。

    本教程介绍以下逻辑的实现:

    示例中的逻辑与界面比您在应用程序中的简单得多。演示项目提供了一种以真实货币计价的形式销售商品以及显示商品目录的可能方案。

    完成商品小组件

    在商品小组件中添加购买按钮,并配置其显示元素。

    下图为小组件结构的示例。

    完成商品小组件脚本

    1. 打开VirtualItemWidget脚本。
    2. 声明购买按钮的变量并在Inspector面板中设置它们的值

    小组件脚本的示例:

    Copy
    Full screen
    Small screen

    using UnityEngine;
    using UnityEngine.UI;
    
    namespace Xsolla.Samples.SellForRealMoney
    {
        public class VirtualItemWidget : MonoBehaviour
        {
            // Declaration of variables for UI elements
         public Text NameText;
            public Text DescriptionText;
            public Text PriceText;
            public Image IconImage;
            public Button BuyButton;
        }
    }
    

    完成显示商品列表的页面控制器

    1. 打开VirtualItemsPage脚本。
    2. 添加处理点击虚拟物品购买按钮的逻辑,如脚本示例中所示。

    注:

    在脚本示例中,商品购买成功时调用了Debug.Log基方法。您还可以添加其他动作,例如物品库显示等。

    默认情况下,支付页面在内置浏览器中打开。如要在外部浏览器中打开,请在Unity编辑器主菜单中前往Window > Xsolla > Edit Settings,然后取消勾选Inspector面板中的Enable in-app browser?复选框。如果要为Android应用使用外部浏览器,建议设置深度链接在用户完成支付后将其重定向到应用中。

    页面脚本示例:

    Copy
    Full screen
    Small screen

    using UnityEngine;
    using Xsolla.Auth;
    using Xsolla.Catalog;
    using Xsolla.Core;
    
    namespace Xsolla.Samples.SellForRealMoney
    {
        public class VirtualItemsPage : MonoBehaviour
        {
            // Declaration of variables for widget's container and prefab
         public Transform WidgetsContainer;
            public GameObject WidgetPrefab;
    
            private void Start()
            {
                // Starting the authentication process
             // Pass the credentials and callback functions for success and error cases
             // The credentials (username and password) are hard-coded for simplicity
             XsollaAuth.SignIn("xsolla", "xsolla", OnAuthenticationSuccess, OnError);
            }
    
            private void OnAuthenticationSuccess()
            {
                // Starting the items request from the store after successful authentication
             // Pass the callback functions for success and error cases
             XsollaCatalog.GetCatalog(OnItemsRequestSuccess, OnError);
            }
    
            private void OnItemsRequestSuccess(StoreItems storeItems)
            {
                // Iterating the items collection
             foreach (var storeItem in storeItems.items)
                {
                    // Skipping items without prices in real money
                 if (storeItem.price == null)
                        continue;
    
                    // Instantiating the widget prefab as child of the container
                 var widgetGo = Instantiate(WidgetPrefab, WidgetsContainer, false);
                    var widget = widgetGo.GetComponent<VirtualItemWidget>();
    
                    // Assigning the values for UI elements
                 widget.NameText.text = storeItem.name;
                    widget.DescriptionText.text = storeItem.description;
    
                    // Assigning the price and currency values for UI elements
                 var price = storeItem.price;
                    widget.PriceText.text = $"{price.amount} {price.currency}";
    
                    // Loading the item image and assigning it to the UI element
                 ImageLoader.LoadSprite(storeItem.image_url, sprite => widget.IconImage.sprite = sprite);
    
                    // Assigning the click listener for the buy button
                 widget.BuyButton.onClick.AddListener(() =>
                    {
                        // Starting the purchase process
                     // Pass the item SKU and callback functions for success and error cases
                     XsollaCatalog.Purchase(storeItem.sku, OnPurchaseSuccess, OnError);
                    });
                }
            }
    
            private void OnPurchaseSuccess(OrderStatus status)
            {
                Debug.Log("Purchase successful");
                // Add actions taken in case of success
         }
    
            private void OnError(Error error)
            {
                Debug.LogError($"Error: {error.errorMessage}");
                // Add actions taken in case of error
         }
        }
    }
    

    以虚拟货币计价的形式销售虚拟物品

    本节介绍如何通过SDK方法实现以虚拟货币形式销售虚拟物品。

    开始之前,需实现在目录中显示虚拟物品。下方示例中我们描述了如何实现虚拟物品的购买。其他商品类型的配置与此类似。

    本教程介绍以下逻辑的实现:

    示例中的逻辑与界面比您在应用程序中的简单得多。演示项目提供了一种以虚拟货币计价的形式销售商品以及显示商品目录的可能方案。

    完成商品小组件

    在商品小组件中添加购买按钮,并配置其显示元素。

    下图为小组件结构的示例。

    完成商品小组件脚本

    1. 打开VirtualItemWidget脚本。
    2. 声明购买按钮的变量并在Inspector面板中设置它们的值

    小组件脚本的示例:

    Copy
    Full screen
    Small screen

    using UnityEngine;
    using UnityEngine.UI;
    
    namespace Xsolla.Samples.SellForVirtualCurrency
    {
        public class VirtualItemWidget : MonoBehaviour
        {
            // Declaration of variables for UI elements
         public Text NameText;
            public Text DescriptionText;
            public Text PriceText;
            public Image IconImage;
            public Button BuyButton;
        }
    }
    

    完成显示商品列表的页面控制器

    1. 打开VirtualItemsPage脚本。
    2. 添加处理点击虚拟物品购买按钮的逻辑,如脚本示例中所示。

    注:

    在脚本示例中,商品购买成功时调用了Debug.Log基方法。您还可以添加其他动作,例如物品库显示虚拟货币余额更改等。

    不需要实现向物品库添加所购商品的逻辑——它会自动完成。

    页面脚本示例:

    Copy
    Full screen
    Small screen

    using System.Linq;
    using UnityEngine;
    using Xsolla.Auth;
    using Xsolla.Catalog;
    using Xsolla.Core;
    
    namespace Xsolla.Samples.SellForVirtualCurrency
    {
        public class VirtualItemsPage : MonoBehaviour
        {
            // Declaration of variables for containers and widget prefabs
         public Transform WidgetsContainer;
            public GameObject WidgetPrefab;
    
            private void Start()
            {
                // Starting the authentication process
             // Pass the credentials and callback functions for success and error cases
             // The credentials (username and password) are hard-coded for simplicity
             XsollaAuth.SignIn("xsolla", "xsolla", OnAuthenticationSuccess, OnError);
            }
    
            private void OnAuthenticationSuccess()
            {
                // After successful authentication starting the request for catalog from store
             // Pass the callback functions for success and error cases
             XsollaCatalog.GetCatalog(OnItemsRequestSuccess, OnError);
            }
    
            private void OnItemsRequestSuccess(StoreItems storeItems)
            {
                // Iterating the items collection
             foreach (var storeItem in storeItems.items)
                {
                    // Skipping items without prices in virtual currency
                 if (storeItem.virtual_prices.Length == 0)
                        continue;
    
                    // Instantiating the widget prefab as child of the container
                 var widgetGo = Instantiate(WidgetPrefab, WidgetsContainer, false);
                    var widget = widgetGo.GetComponent<VirtualItemWidget>();
    
                    // Assigning the values for UI elements
                 widget.NameText.text = storeItem.name;
                    widget.DescriptionText.text = storeItem.description;
    
                    // Assigning the price and currency values for UI elements
                 // The first price is used for the sake of simplicity
                 var price = storeItem.virtual_prices.First(x => x.is_default);
                    widget.PriceText.text = $"{price.name}: {price.amount}";
    
                    // Loading the item image and assigning it to the UI element
                 ImageLoader.LoadSprite(storeItem.image_url, sprite => widget.IconImage.sprite = sprite);
    
                    // Assigning the click listener for the buy button
                 widget.BuyButton.onClick.AddListener(() =>
                    {
                        // Starting the purchase process
                     // Pass the item SKU, the price virtual currency SKU and callback functions for success and error cases
                     XsollaCatalog.PurchaseForVirtualCurrency(storeItem.sku, price.sku, OnPurchaseSuccess, OnError);
                    });
                }
            }
    
            private void OnPurchaseSuccess(OrderStatus status)
            {
                Debug.Log("Purchase successful");
                // Add actions taken in case of success
         }
    
            private void OnError(Error error)
            {
                Debug.LogError($"Error: {error.errorMessage}");
                // Add actions taken in case of error
         }
        }
    }
    

    显示虚拟货币余额

    本教程介绍如何使用SDK方法在应用中显示虚拟货币的余额。

    示例中的逻辑与界面比您实际在应用程序中的要简单得多。演示项目提供了一种可能的游戏内商店商品目录实现方案。

    创建显示余额的小组件

    1. 创建一个空游戏对象。方法是前往主菜单,然后选择GameObject > Create Empty
    2. Hierarchy面板拖动一个游戏对象到Project面板,以转换预制件中创建的游戏对象。
    3. 选择一个创建的预制件,然后在Inspector面板中单击Open Prefab
    4. 将以下UI元素添加为预制件子对象并配置其视觉显示:
      • 小组件背景图片
      • 虚拟货币名称
      • 虚拟货币数量
      • 虚拟货币图片

    下图为小组件结构的示例。

    创建显示余额的小组件脚本

    1. 创建一个继承自MonoBehaviour基类的脚本VirtualCurrencyWidget
    2. 声明商品小组件界面元素的变量并Inspector面板中设置它们的值

    小组件脚本的示例:

    Copy
    Full screen
    Small screen

    using UnityEngine;
    using UnityEngine.UI;
    
    namespace Xsolla.Samples.DisplayVirtualCurrencyBalance
    {
        public class VirtualCurrencyWidget : MonoBehaviour
        {
            // Declaration of variables for UI elements
         public Text NameText;
            public Text AmountText;
            public Image IconImage;
        }
    }
    

    创建包含虚拟货币列表的页面

    1. 在场景上创建一个空游戏对象。方法是前往主菜单,然后选择GameObject > Create Empty
    2. 将以下UI元素添加为预制件子对象并配置其视觉显示:
      • 页面背景图片
      • 小组件显示区域

    下图为页面结构的示例。

    创建包含虚拟货币列表页面的控制器

    1. 创建继承自MonoBehaviour基类的脚本VirtualCurrenciesPage
    2. 声明以下变量:
      • WidgetsContainer — 小组件的容器
      • WidgetPrefab — 余额显示小组件预制件

    1. 将脚本附加到页面游戏对象上:
      1. Hierarchy面板中选择一个对象。
      2. Inspector面板中,单击Add Component,然后选择一个VirtualCurrenciesPage脚本。

    1. Inspector面板中设置变量的值。
    2. 添加登录逻辑和获取虚拟货币列表的逻辑,如脚本示例中所示。

    注:
    在脚本示例中,我们使用了演示帐户的凭证进行登录(用户名:xsolla,密码:xsolla)。

    页面控制器脚本示例:

    Copy
    Full screen
    Small screen

    using UnityEngine;
    using Xsolla.Auth;
    using Xsolla.Core;
    using Xsolla.Inventory;
    
    namespace Xsolla.Samples.DisplayVirtualCurrencyBalance
    {
        public class VirtualCurrenciesPage : MonoBehaviour
        {
            // Declaration of variables for widget's container and prefab
         public Transform WidgetsContainer;
            public GameObject WidgetPrefab;
    
            private void Start()
            {
                // Starting the authentication process
             // Pass the credentials and callback functions for success and error cases
             // The credentials (username and password) are hard-coded for simplicity
             XsollaAuth.SignIn("xsolla", "xsolla", OnAuthenticationSuccess, OnError);
            }
    
            private void OnAuthenticationSuccess()
            {
                // Starting the virtual currencies request from the store after successful authentication
             // Pass the callback functions for success and error cases
             XsollaInventory.GetVirtualCurrencyBalance(OnBalanceRequestSuccess, OnError);
            }
    
            private void OnBalanceRequestSuccess(VirtualCurrencyBalances balance)
            {
                // Iterating the virtual currency balances collection
             foreach (var balanceItem in balance.items)
                {
                    // Instantiating the widget prefab as child of the container
                 var widgetGo = Instantiate(WidgetPrefab, WidgetsContainer, false);
                    var widget = widgetGo.GetComponent<VirtualCurrencyWidget>();
    
                    // Assigning the values for UI elements
                 widget.NameText.text = balanceItem.name;
                    widget.AmountText.text = balanceItem.amount.ToString();
    
                    ImageLoader.LoadSprite(balanceItem.image_url, sprite => widget.IconImage.sprite = sprite);
                }
            }
    
            private void OnError(Error error)
            {
                Debug.LogError($"Error: {error.errorMessage}");
                // Add actions taken in case of error
         }
        }
    }
    

    下图为脚本的运行结果。

    显示物品库中的物品

    本教程介绍如何使用SDK方法显示用户物品库中的商品。

    示例中的逻辑与界面比您在应用程序中的简单得多。演示项目提供了一种可能的物品库实现方案。

    创建商品小组件

    1. 创建一个空游戏对象。方法是前往主菜单,然后选择GameObject > Create Empty
    2. Hierarchy面板拖动一个游戏对象到Project面板,以转换预制件中创建的游戏对象。
    3. 选择一个创建的预制件,然后在Inspector面板中单击Open Prefab
    4. 将以下UI元素添加为预制件子对象并配置其视觉显示:
      • 商品背景图片
      • 商品名称
      • 商品描述
      • 商品数量
      • 商品图片

    下图为小组件结构的示例。

    创建商品小组件脚本

    1. 创建一个继承自MonoBehaviour基类的脚本InventoryItemWidget
    2. 声明商品小组件界面元素的变量并Inspector面板中设置它们的值

    小组件脚本的示例:

    Copy
    Full screen
    Small screen

    using UnityEngine;
    using UnityEngine.UI;
    
    namespace Xsolla.Samples.DisplayItemsInInventory
    {
        public class InventoryItemWidget : MonoBehaviour
        {
            // Declaration of variables for UI elements
         public Text NameText;
            public Text DescriptionText;
            public Text QuantityText;
            public Image IconImage;
        }
    }
    

    创建显示物品库的页面

    1. 在场景上创建一个空游戏对象。方法是前往主菜单,然后选择GameObject > Create Empty
    2. 将以下UI元素添加为预制件子对象并配置其视觉显示:
      • 页面背景图片
      • 商品小组件显示区域

    下图为页面结构的示例。

    创建页面控制器

    1. 创建继承自MonoBehaviour基类的脚本InventoryItemsPage
    2. 声明以下变量:
      • WidgetsContainer — 商品小组件的容器
      • WidgetPrefab — 商品小组件预制件

    1. 将脚本附加到页面游戏对象上:
      1. Hierarchy面板中选择一个对象。
      2. Inspector面板中,单击Add Component,然后选择一个InventoryItemsPage脚本。

    1. Inspector面板中设置变量的值。
    2. 添加登录逻辑和获取物品库中商品列表的逻辑。

    注:
    在脚本示例中,我们使用了演示帐户的凭证进行登录(用户名:xsolla,密码:xsolla)。

    页面控制器脚本示例:

    Copy
    Full screen
    Small screen

    using UnityEngine;
    using Xsolla.Auth;
    using Xsolla.Core;
    using Xsolla.Inventory;
    
    namespace Xsolla.Samples.DisplayItemsInInventory
    {
        public class InventoryItemsPage : MonoBehaviour
        {
            // Declaration of variables for widget's container and prefab
         public Transform WidgetsContainer;
            public GameObject WidgetPrefab;
    
            private void Start()
            {
                // Starting the authentication process
             // Pass the credentials and callback functions for success and error cases
             // The credentials (username and password) are hard-coded for simplicity
             XsollaAuth.SignIn("xsolla", "xsolla", OnAuthenticationSuccess, OnError);
            }
    
            private void OnAuthenticationSuccess()
            {
                // Starting the items request from the store after successful authentication
             // Pass the callback functions for success and error cases
             XsollaInventory.GetInventoryItems(OnItemsRequestSuccess, OnError);
            }
    
            private void OnItemsRequestSuccess(InventoryItems inventoryItems)
            {
                // Iterating the items collection
             foreach (var inventoryItem in inventoryItems.items)
                {
                    // Skipping virtual currency items
                 if (inventoryItem.VirtualItemType == VirtualItemType.VirtualCurrency)
                        continue;
    
                    // Instantiating the widget prefab as child of the container
                 var widgetGo = Instantiate(WidgetPrefab, WidgetsContainer, false);
                    var widget = widgetGo.GetComponent<InventoryItemWidget>();
    
                    // Assigning the values for UI elements
                 widget.NameText.text = inventoryItem.name;
                    widget.DescriptionText.text = inventoryItem.description;
                    widget.QuantityText.text = inventoryItem.quantity.ToString();
    
                    // Loading the item image and assigning it to the UI element
                 ImageLoader.LoadSprite(inventoryItem.image_url, sprite => widget.IconImage.sprite = sprite);
                }
            }
    
            private void OnError(Error error)
            {
                Debug.LogError($"Error: {error.errorMessage}");
                // Add actions taken in case of error
         }
        }
    }
    

    下图为脚本的运行结果。

    您的进度
    感谢您的反馈!

    有用链接

    上次更新时间: 2023年5月29日

    发现了错别字或其他内容错误? 请选择文本,然后按Ctrl+Enter。

    报告问题
    我们非常重视内容质量。您的反馈将帮助我们做得更好。
    请留下邮箱以便我们后续跟进
    感谢您的反馈!