Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
930 views
in Technique[技术] by (71.8m points)

c# - How to save bool to PlayerPrefs Unity

I have a payment system for my game set up here's my code :

 void Start()
 {
     T55.interactable = false;
     Tiger2.interactable = false;
     Cobra.interactable = false;
 }

 public void ProcessPurchase (ShopItem item)
 {
     if(item .SKU =="tank")
     {
         StoreHandler .Instance .Consume (item );
     }
 }

 public void OnConsumeFinished (ShopItem item)
 {
     if(item .SKU =="tank")
     {
         T55.interactable = true;
         Tiger2.interactable = true;
         Cobra.interactable = true;
     }
 }

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

PlayerPrefs does not have an overload for a boolean type. It only supports string, int and float.

You need to make a function that converts true to 1 and false to 0 then the the PlayerPrefs.SetInt and PlayerPrefs.GetInt overload that takes int type.

Something like this:

int boolToInt(bool val)
{
    if (val)
        return 1;
    else
        return 0;
}

bool intToBool(int val)
{
    if (val != 0)
        return true;
    else
        return false;
}

Now, you can easily save bool to PlayerPrefs.

void saveData()
{
    PlayerPrefs.SetInt("T55", boolToInt(T55.interactable));
    PlayerPrefs.SetInt("Tiger2", boolToInt(T55.interactable));
    PlayerPrefs.SetInt("Cobra", boolToInt(T55.interactable));
}

void loadData()
{
    T55.interactable = intToBool(PlayerPrefs.GetInt("T55", 0));
    Tiger2.interactable = intToBool(PlayerPrefs.GetInt("Tiger2", 0));
    Cobra.interactable = intToBool(PlayerPrefs.GetInt("Cobra", 0));
}

If you have many variables to save, use Json and PlayerPrefs instead of saving and loading them individually. Here is how to do that.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...