PlayerPrefs.SetInt和.GetInt具有不希望的效果

本文关键字:希望 SetInt GetInt PlayerPrefs | 更新日期: 2023-09-27 17:59:15

我在Unity3D中有一个应用程序,我正在为android制作,你可以收集游戏货币硬币。每次我开始游戏时,我的硬币数量都会初始化为0,尽管我正在使用setInt和getInt尝试保存硬币数量,以便玩家下次玩游戏时使用。

完全不确定为什么不保存coinAmount,有什么想法吗?(可能是因为我有点笨)。

 using UnityEngine;
 using System.Collections;
 public class pickupCoin : MonoBehaviour {
public int amountOfCoins;
public AudioClip coinPing;
public AudioSource playerAudio;
void Start () {

    if(PlayerPrefs.GetInt("TotalCoinsPlayerPrefs") == null){
        PlayerPrefs.SetInt("TotalCoinsPlayerPrefs", 0);
    }
    amountOfCoins = PlayerPrefs.GetInt("TotalCoinsPlayerPrefs");
}

void OnCollisionEnter(Collision other){
    if(other.gameObject.name.Contains("coin")){
        playerAudio.PlayOneShot(coinPing);
        amountOfCoins+=1;
        PlayerPrefs.SetInt("TotalCoinsPlayerPrefs", amountOfCoins);
        Debug.Log("amount of coins is: " + amountOfCoins);
        Debug.Log("Player Prefs Coin Amount Is" + PlayerPrefs.GetInt("TotalCoinsPlayerPrefs").ToString());
        Destroy(other.gameObject);

    }
}

}

PlayerPrefs.SetInt和.GetInt具有不希望的效果

用于检查PlayerPref是否存在(PlayerPrefs.GetInt("TotalCoinsPlayerPrefs") == null)的测试是"错误的"。执行该任务的正确方法是调用HasKey函数。

基本上,我认为您当前的测试总是返回TRUE,并且在游戏开始时,您的PlayerPref的内容总是初始化为0

您的Start函数应该是这样的。

void Start () {
    amountOfCoins = PlayerPrefs.GetInt("TotalCoinsPlayerPrefs"); // handles case it doesn't exist and provides a default value of zero unless otherwise specified
}

我刚刚证实你不必打PlayerPrefs.Save()

你能验证这个脚本是否适合你吗。

using UnityEngine;
using System.Collections;
public class PlayerPrefsScript : MonoBehaviour {
public int amountOfCoins;
void Start () {
    amountOfCoins = PlayerPrefs.GetInt("TotalCoinsPlayerPrefs");
}
void OnGUI()
{
    if (GUI.Button (new Rect (0, 0, 100, 50), "Coins: " + amountOfCoins)) {
        amountOfCoins++;    
    }
}
void OnDestroy(){
    PlayerPrefs.SetInt ("TotalCoinsPlayerPrefs", amountOfCoins);
}
}