本文介绍了如何将 bool 保存到 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;
     }
 }

现在每次玩家在游戏中购买东西时,我的 3 个按钮都变得难以处理;但问题是每次他关闭游戏时,棘手都会回到错误的方式.

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?

推荐答案

PlayerPrefs没有布尔类型的重载.它只支持字符串、整数和浮点数.

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

您需要创建一个函数,将 true 转换为 1 并将 false 转换为 0 然后PlayerPrefs.SetIntPlayerPrefs.GetInt 重载,采用 int 类型.

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.

像这样:

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

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

现在,您可以轻松地将 bool 保存到 PlayerPrefs.

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));
}

如果您有很多变量要保存,请使用 Json 和 PlayerPrefs,而不是单独保存和加载它们.这里是如何做到这一点.

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

这篇关于如何将 bool 保存到 PlayerPrefs Unity的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 20:04