如何将bool保存到PlayerPrefs Unity [英] How to save bool to PlayerPrefs Unity

查看:424
本文介绍了如何将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.

我是否应该保存该过程,以便玩家不必再次购买就可以将其设置为true?

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆