我在 Android 上遇到 PlayerPrefs 问题。我希望我的教程只显示一次,所以我编写了这段代码:
void Awake(){
firstTime = false;
hasPlayed = PlayerPrefs.GetInt ("hasPlayed");
if (hasPlayed == 0) {
firstTime = true;
} else {
PlayerPrefs.SetInt ("hasPlayed", 1);
firstTime = false;
PlayerPrefs.Save ();
}
}
在手机上构建和测试后,apk 不会在/data 或其他任何地方创建任何文件夹,因此,每次我运行游戏时都会显示教程。
最佳答案
PlayerPrefs.GetInt
采用另一个参数,如果提供的键不不存在,您可以使用该参数返回一个值。检查 hasPlayed
键是否存在,默认值为 0
。如果键不存在,它将返回默认值 0
。
如果它返回 0
,请将 hasPlayed
设置为 1
,然后播放您的教程。如果返回1
,则表示该教程之前已经播放过。类似于 this问题,但需要一点点修改。
它应该是这样的:
void Start()
{
//Check if hasPlayed key exist.
if (PlayerPrefs.GetInt("hasPlayed", 0) == 1)
{
hasPlayed();
}
else
{
//Set hasPlayed to true
PlayerPrefs.SetInt("hasPlayed", 1);
PlayerPrefs.Save();
notPlayed();
}
}
void hasPlayed()
{
Debug.Log("Has Played");
//Don't do anything
}
void notPlayed()
{
Debug.Log("Not Played");
//Play your tutorial
}
//Call to reset has played
void resetHasPlayed()
{
PlayerPrefs.DeleteKey("hasPlayed");
}
关于c# - PlayerPrefs 不适用于 Android 和编辑器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38620217/