首页 > 解决方案 > 为什么 PlayerPrefs 中没有减去数字?

问题描述

大家好在我的代码中,当你点击按钮时,应该减去一个数字并保存在 PlayerPrefs 中,减去数字,但不保存。我还了解到因为OnApplicationQuit方法退出游戏时会保存号码,如何让号码正常保存?

    public class Chest_Money : MonoBehaviour
{
    
    public int NumCharector;
    public int money;
    public int Rand;

    public Text text;

    public GameObject NotMoney;
    public GameObject[] Charectors;
    public GameObject Panel;
    public GameObject Panel2;

    public bool bla2;

    
    void Start()
    {
        money = PlayerPrefs.GetInt("Money_S", 0);
    }
    private void Awake()
    {
        
        
    }
#if UNITY_ANDROID && !UNITY_EDITOR
private void OnApplicationPause(bool pause){
            if(pause){
                //PlayerPrefs.SetInt("Money_S" , money);
                
            }
        }
#endif
    private void OnApplicationQuit()
    {
        PlayerPrefs.SetInt("Money_S" , money);
        
    }
    
    void Update()
    {
        
        PlayerPrefs.SetInt("Money_S", money);
        text.text = "$:" + money;
        
        if(bla2 == true){
            Panel2.SetActive(true);
            
        }
    }
    public void Chest(){
        if(money >= 100){
            money -= 100;
            PlayerPrefs.SetInt("Money_S", money);
            
            
            StartCoroutine(Wait2());
        }
        else {
            NotMoney.SetActive(true);
            StartCoroutine(Wait4());
        }
        
    }
    
   
    IEnumerator Wait4(){
        yield return new WaitForSeconds(2);
        NotMoney.SetActive(false);
    }
    IEnumerator Wait2()
    {
        yield return new WaitForSeconds(0);
        SceneManager.LoadScene("Scins");
    }
}

标签: c#unity3d

解决方案


一般来说,您可以/应该使用PlayerPrefs.Save强制保存某些检查点

默认情况下,Unity 在OnApplicationQuit(). 在游戏崩溃或过早退出的情况下,您可能希望在游戏中合理的“检查点”处编写 PlayerPrefs。此函数将写入磁盘可能会导致小问题,因此不建议在实际游戏过程中调用。

然后我还建议您使用类似的属性

private int _money;

public int money
{
    get => _money;
    set
    {
        _money = value;
        PlayerPrefs.SetInt("Money_S");
        PlayerPrefs.Save();

        text.text = "$:" + money;
    }
}

因此,它只会更新文本并在实际更改后保存值。

这样您就不需要更新文本Update.


推荐阅读