Search Unity

How to save bool to PlayerPrefs

Discussion in 'Scripting' started by DevilArash, Dec 10, 2016.

  1. DevilArash

    DevilArash

    Joined:
    Nov 26, 2016
    Posts:
    1
    Hi I have a payment system for my game set up here's my code :

    1. usingUnityEngine;
    2. usingSystem.Collections;
    3. usingCafeBazarIab;
    4. usingUnityEngine.UI ;
    5. publicclassStoreEventHandler:MonoBehaviour,IStoreEventHandler
    6. {
    7. publicButton T55;
    8. publicButtonTiger2;
    9. publicButtonCobra;
    10. #region IStoreEventHandler implementation
    11. voidStart()
    12. {
    13. T55.interactable =false;
    14. Tiger2.interactable =false;
    15. Cobra.interactable =false;
    16. }
    17. publicvoidProcessPurchase(ShopItem item)
    18. {
    19. if(item .SKU =="tank")
    20. {
    21. StoreHandler.Instance.Consume(item );
    22. }
    23. }
    24. publicvoidOnConsumeFinished(ShopItem item)
    25. {
    26. if(item .SKU =="tank")
    27. {
    28. T55.interactable =true;
    29. Tiger2.interactable =true;
    30. Cobra.interactable =true;
    31. }
    32. }
    33. }

    now each time the player buy something in the game the intractability of my 3 buttons goes to true; but the problem is each time he closes the game the intractability goes back to false how; should i save the process so the player doesn't have to buy again to set them back to true ?
     
  2. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    2,205
  3. TaleOf4Gamers

    TaleOf4Gamers

    Joined:
    Nov 15, 2013
    Posts:
    802
  4. free-divbyzero

    free-divbyzero

    Joined:
    Dec 11, 2015
    Posts:
    9
    You can add property (with setter/getter) to data class. For example:

    Code (CSharp):
    1. string _tankKey = "tankKey";
    2. bool? _hasBoughtTank;
    3. public bool hasBoughtTank
    4. {
    5.     get
    6.     {
    7.         if (_hasBoughtTank == null)
    8.         {
    9.             if (PlayerPrefs.HasKey(_tankKey))
    10.             {
    11.                 _hasBoughtTank = (PlayerPrefs.GetInt(_tankKey) == 1);
    12.             }
    13.             else
    14.             {
    15.                 _hasBoughtTank = false;
    16.             }
    17.         }
    18.  
    19.         return _hasBoughtTank.Value;
    20.     }
    21.     set
    22.     {
    23.         _hasBoughtTank = value;
    24.  
    25.         PlayerPrefs.SetInt(_tankKey, (_hasBoughtTank.HasValue && _hasBoughtTank.Value) ? 1 : 0);
    26.         PlayerPrefs.Save();
    27.     }
    28. }
    If you want to save bool value like PlayerPrefs.SetBool - try PPE [PlayerPrefs Extension] or another assets for PlayerPrefs.
     
  5. Zaflis

    Zaflis

    Joined:
    May 26, 2014
    Posts:
    432
    Or simply use SetInt(), where 1 means true and 0 false. (Making a property seems complex)
     
    KittyAnn and diegomendes like this.
unityunity