【问题标题】:PlayerPrefs.SetInt and .GetInt having undesired effectPlayerPrefs.SetInt 和 .GetInt 具有不良影响
【发布时间】:2014-04-21 12:49:23
【问题描述】:

几乎我在 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);



    }

}

}

【问题讨论】:

    标签: c# android unity3d save


    【解决方案1】:

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

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

    【讨论】:

    • 不,它永远不会返回 true,因为 GetInt 将始终返回默认值。如果不指定,则默认为 0。
    【解决方案2】:

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

    【讨论】:

    • 嘿Nunery 感谢您的评论。我没有调用 PlayerPrefs.Save(),但我正在使用 playerprefs 作为我的高分,这似乎与类似的代码一起工作得很好,所以我有点困惑
    • '游戏中的检查点。此函数将写入磁盘可能会导致小问题,因此不建议在实际游戏过程中调用。 docs.unity3d.com/Documentation/ScriptReference/…Android 游戏真的“退出”了吗?
    • 我只是将我的代码更改为那个,并且还调用了 PlayerPrefs.Save() 并且仍然没有:/。当我 debug.log playerPrefs.GetInt("TotalCoinsPlayerPrefs") 它显示它捡起一枚硬币并且值为 1,但是当我重置游戏(按两次播放按钮)时,它再次重置为 0
    • 你试过修改后的Start()函数吗?
    猜你喜欢
    • 2021-02-04
    • 1970-01-01
    • 2021-12-08
    • 1970-01-01
    • 2011-12-19
    • 2011-12-29
    • 1970-01-01
    • 2011-01-17
    • 2018-10-07
    相关资源
    最近更新 更多