自学内容网 自学内容网

【Unity基础】Unity用脚本实现内购(IAP)

本文介绍了如何使用脚本实现内购功能。

先看下脚本,代码中根据执行过程添加了序号。

using UnityEngine;
using UnityEngine.Purchasing;
using UnityEngine.UI;

namespace Samples.Purchasing.Core.BuyingConsumables
{
    public class BuyingConsumables : MonoBehaviour, IStoreListener
    {
        IStoreController m_StoreController; // The Unity Purchasing system.

        //Your products IDs. They should match the ids of your products in your store.
        public string coins100ProductId = "com.xxx.unitygame.coins100";
        public string coins500ProductId = "com.xxx.unitygame.coins500";

        public Text CoinsCountText;
        int m_GoldCount;

        // 1. 开始入口
        void Start()
        {
            Debug.Log("1. Start begin...");
            InitializePurchasing();
            UpdateUI();
            Debug.Log("1. Start end...");
        }

        // 2. 初始化内购
        void InitializePurchasing()
        {
            Debug.Log("2. InitializePurchasing begin...");

            // 创建实例
            var builder = ConfigurationBuilder.Instance(StandardPurchasingModule.Instance());

            // 添加内购商品
            //Add products that will be purchasable and indicate its type.
            builder.AddProduct(coins100ProductId, ProductType.Consumable);
            builder.AddProduct(coins500ProductId, ProductType.Consumable);

            // 初始化
            UnityPurchasing.Initialize(this, builder);

            Debug.Log("2. InitializePurchasing end...");
        }

        // 4. Button事件处理
        public void BuyGold(int count)
        {
            Debug.Log($"4. Player buy gold:{count}");
            Debug.Log("4. BuyGold begin...");
            if (count == 100)
            {
                m_StoreController.InitiatePurchase(coins100ProductId);
            }
            else if(count == 500)
            {
                 m_StoreController.InitiatePurchase(coins500ProductId);
            }
            Debug.Log("4. BuyGold end...");
        }

        // 3. 初始化完成
        public void OnInitialized(IStoreController controller, IExtensionProvider extensions)
        {
            Debug.Log("3. OnInitialized begin...");
            Debug.Log("3. In-App Purchasing successfully initialized");
            m_StoreController = controller;
            Debug.Log("3. OnInitialized end...");
        }

        public void OnInitializeFailed(InitializationFailureReason error)
        {
            Debug.Log($"3. In-App Purchasing initialize failed: {error}");
        }

        // 5. 购买处理
        public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args)
        {
            Debug.Log("5. ProcessPurchase begin...");

            //Retrieve the purchased product
            var product = args.purchasedProduct;

            //Add the purchased product to the players inventory
            if (product.definition.id == coins100ProductId)
            {
                AddGold(100);
            }
            else if (product.definition.id == coins500ProductId)
            {
                AddGold(500);
            }

            Debug.Log($"5. Purchase Complete - Product: {product.definition.id}");

            Debug.Log("5. ProcessPurchase end...");

            //We return Complete, informing IAP that the processing on our side is done and the transaction can be closed.
            return PurchaseProcessingResult.Complete;
        }

        public void OnPurchaseFailed(Product product, PurchaseFailureReason failureReason)
        {
            Debug.Log($"5. Purchase failed - Product: '{product.definition.id}', PurchaseFailureReason: {failureReason}");
        }

        // 6. 完成购买事件
        void AddGold(int count)
        {
            Debug.Log("6. AddGold begin...");

            m_GoldCount +=count;
            UpdateUI();

            Debug.Log("6. AddGold end...");
        }

        // 7. 更新UI
        void UpdateUI()
        {
            Debug.Log("7. UpdateUI begin...");
            CoinsCountText.text = $"Your Coins: {m_GoldCount}";
            Debug.Log("7. UpdateUI end...");
        }
    }
}

根据代码分析,可以看出在Unity中实现内购的过程分为几个关键步骤:

  1. 初始化内购:在Start方法中调用InitializePurchasing,创建一个ConfigurationBuilder实例并添加可购买的产品(如金币)。通过UnityPurchasing.Initialize初始化内购系统。

  2. 处理购买请求:当玩家点击购买按钮时,调用BuyGold方法。根据购买的金币数量,调用m_StoreController.InitiatePurchase发起购买请求。

  3. 购买成功处理:实现OnInitializedProcessPurchase方法。在OnInitialized中确认内购系统已成功初始化。在ProcessPurchase中根据购买的产品ID更新玩家的金币数量。

  4. 错误处理:实现OnInitializeFailedOnPurchaseFailed方法,以便在初始化或购买失败时进行日志记录和处理。

  5. 更新UI:通过UpdateUI方法更新显示玩家当前的金币数量,确保界面与数据保持同步。


原文地址:https://blog.csdn.net/tealcwu/article/details/142862895

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!