Unity IAP сообщает об успешном выполнении, но не может обновить матрицу монет для игровой валюты - PullRequest
0 голосов
/ 23 января 2020

Моя проблема, которая беспокоила меня в течение пяти дней, заключается в том, что мой скрипт IAP, когда я нажимаю кнопку покупки, сообщает, что покупка прошла успешно, но не удалось обновить систему монет в игре для игровой валюты. В игре используются три сценария - сценарий покупок, сценарий UsersProgress и сценарий CoinCounter. Предполагается, что Покупатель вызывает сценарий UsersProgress, но как только нажата кнопка «Покупки», единство Consell утверждает, что покупка прошла успешно. Но не обновляет матрицу монет, вызывая сценарии и обновляя.

Первый сценарий Покупатель сценарий

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Purchasing;
using EasyMobile;
using UnityEngine.Purchasing.Extension;


[RequireComponent(typeof(Text))] //just added
public class Purchas : MonoBehaviour
{
 IAPProduct[] products = InAppPurchasing.GetAllIAPProducts();

 int coins = 0;

 string Item { get; set; } //added
 Price Price { get; set; } //added

 Text label; //added

 [SerializeField]
 private Text coinsText;

 int PurchaseProgress
 {
     get => UserProgress.Current.GetItemPurchaseProgress(Item);
     set => UserProgress.Current.SetItemPurchaseProgress(Item, value);
 }

 //just added this//
 void OnProgressUpdate()
 {
     label.text = UserProgress.Current.Coins.ToString();
 }

 public void SetPrice(string item, Price price) //just added
 {
     Item = item;
     Price = price;


     if (price.value <= UserProgress.Current.GetItemPurchaseProgress(item));

 }

 // Start is called before the first frame update
 void start()
 {
     InAppPurchasing.InitializePurchasing();
     bool isInitialized = InAppPurchasing.IsInitialized();
     //just added below
     label = GetComponent<Text>();

     OnProgressUpdate();
     UserProgress.Current.ProgressUpdate += OnProgressUpdate;
 }
 //added below just now
 void OnDestroy()
 {
     UserProgress.Current.ProgressUpdate -= OnProgressUpdate;
 }

 void Awake()
 {
     if (!RuntimeManager1.IsInitialized())
         RuntimeManager1.Init();
 }

 void update()
 {
     coinsText.text = coins.ToString();
 }

 private void OnEnable()
 {
     InAppPurchasing.PurchaseCompleted -= PurchaseCompletedHandler;
     InAppPurchasing.PurchaseFailed -= PurchaseFailedHandler;
 }

 private void OnDisable()
 {
     InAppPurchasing.PurchaseCompleted -= PurchaseCompletedHandler;
     InAppPurchasing.PurchaseFailed -= PurchaseFailedHandler;
 }

 private void PurchaseFailedHandler(IAPProduct product)
 {
     NativeUI.Alert("Error", "The purchase of product" + product.Name + " has failed.");
 }

 // Successful purchase handler
 void PurchaseCompletedHandler(IAPProduct product)
 {
     // Compare product name to the generated name constants to determine which product was bought
     switch (product.Name)
     {
         case EM_IAPConstants.Product_200_Coins:
             Debug.Log("Product_200_Coins was purchased. The user should be granted it now.");
             UserProgress.Current.Coins += coins += 200; //just changed
             break;
         case EM_IAPConstants.Product_500_Coins:
             Debug.Log("500_Coins was purchased. The user should be granted it now.");
             UserProgress.Current.Coins += coins += 500; //just changed
             break;
         case EM_IAPConstants.Product_1100_Coins:
             Debug.Log("1100_Coins was purchased. the user should be granted it now");
             UserProgress.Current.Coins += coins += 1100; //just changed
             break;

     }
 }

 public void BuyComplete(UnityEngine.Purchasing.Product product)
 {
     //purchase was successful
 }

 public void BuyFailed(UnityEngine.Purchasing.Product product, UnityEngine.Purchasing.PurchaseFailureReason failureReason)
 {
     //purchase was unsuccessful
 }

 public void PurchasCoinsPack()
 {
     InAppPurchasing.Purchase(EM_IAPConstants.Product_200_Coins);

     InAppPurchasing.Purchase(EM_IAPConstants.Product_500_Coins);

     InAppPurchasing.Purchase(EM_IAPConstants.Product_1100_Coins);
 }

}

В этом случае при совершении покупки предполагается вызвать и обновить следующие два сценария

using System;
 using System.Collections.Generic;
 using UnityEngine;

 [Serializable]
 public class UserProgress
 {
     [Serializable]
     struct PurchaseProgress
     {
         public string item;
         public int value;

         public PurchaseProgress(string item, int value)
         {
             this.item = item;
             this.value = value;
         }
     }

     static UserProgress current;

     public event Action ProgressUpdate = delegate { };

     Dictionary<string, GameState> gameStates = new Dictionary<string, GameState>();

     [SerializeField]
     int coins;

     [SerializeField]
     List<string> purchasedItems = new List<string>();

     [SerializeField]
     List<PurchaseProgress> purchaseInProgress = new List<PurchaseProgress>();

     [SerializeField]
     string currentGameId;
     [SerializeField]
     string currentThemeId;

     public static UserProgress Current
     {
         get
         {
             if (current != null)
                 return current;

             string progressJson = PlayerPrefs.GetString("UserProgress", "{}");
             Debug.Log("UserProgress : " + progressJson);
             current = JsonUtility.FromJson<UserProgress>(progressJson);

             return current;
         }
     }

     public int Coins
     {
         get => coins;
         set
         {
             coins = value;

             Save();

             ProgressUpdate.Invoke();
         }
     }

     public string CurrentGameId
     {
         get => currentGameId;
         set
         {
             currentGameId = value;

             Save();

             ProgressUpdate.Invoke();
         }
     }

     public string CurrentThemeId
     {
         get => currentThemeId;
         set
         {
             currentThemeId = value;

             Save();

             ProgressUpdate.Invoke();
         }
     }

     public bool IsItemPurchased(string item)
     {
         return purchasedItems.Contains(item);
     }

     public void OnItemPurchased(string item)
     {
         purchasedItems.Add(item);

         Save();

         ProgressUpdate.Invoke();
     }

     public int GetItemPurchaseProgress(string item)
     {
         PurchaseProgress purchaseProgress = purchaseInProgress.Find(p => p.item == item);
         return purchaseProgress.value;
     }

     public void SetItemPurchaseProgress(string item, int value)
     {
         purchaseInProgress.RemoveAll(p => p.item == item);
         purchaseInProgress.Add(new PurchaseProgress(item, value));

         Save();

         ProgressUpdate.Invoke();
     }

     public T GetGameState<T>(string id) where T : GameState
     {
         if (string.IsNullOrEmpty(id))
             return null;

         if (gameStates.ContainsKey(id) && gameStates[id] is T)
             return (T) gameStates[id];

         if (!PlayerPrefs.HasKey(id))
             return null;

         if (gameStates.ContainsKey(id))
             gameStates.Remove(id);

         GameState gameState = JsonUtility.FromJson<T>(PlayerPrefs.GetString(id));
         gameStates.Add(id, gameState);

         return (T) gameState;
     }

     public void SetGameState<T>(string id, T state) where T : GameState
     {
         if (gameStates.ContainsKey(id))
             gameStates[id] = state;
         else
             gameStates.Add(id, state);
     }

     public void SaveGameState(string id)
     {
         if (gameStates.ContainsKey(id))
             PlayerPrefs.SetString(id, JsonUtility.ToJson(gameStates[id]));
     }

     public void Save()
     {
         string progressJson = JsonUtility.ToJson(this);
         PlayerPrefs.SetString("UserProgress", progressJson);
     }
 }

Обновление через UsersProgress Я знаю, что это происходит потому, что рекламный скрипт вызывает те же скрипты и обновляет их, когда надстройка отслеживает матрицу монет, но также обновляет следующий скрипт CoinCounter ниже

    using UnityEngine;
    using UnityEngine.UI;

    [RequireComponent(typeof(Text))]
 public class CoinsCounter : MonoBehaviour
 {
 Text label;

 void OnProgressUpdate()
 {
     label.text = UserProgress.Current.Coins.ToString();
 }

 void Start()
 {
     label = GetComponent<Text>();

     OnProgressUpdate();
     UserProgress.Current.ProgressUpdate += OnProgressUpdate;
 }

 void OnDestroy()
 {
     UserProgress.Current.ProgressUpdate -= OnProgressUpdate;
 }
}

Я пытался сделать различные обратные вызовы и обновления, но, похоже, ничего не работает.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...