我使用 PlayerPerfabs 来存储玩家数据,例如玩家已解锁的级别以及在游戏过程中获得的分数,并且我希望在游戏过程中定期更新 PlayerPerfabs 数据(例如每 5 秒),所以我创建了一个名为ApplicationModel 保存全局数据,例如积分玩家获取级别信息等。
public ApplicationModel: MonoBehaviour{
public static int point {get;set;}
//try to load the PlayerPerfabs when start game.
static ApplicationModel(){
if(PlayerPerfabs.HasKey("point")){
point = PlayerPerfabs.GetInt("point");
}else{
point = 0;
}
}
//coroutine to set the data to PlayerPerfabs
IEnumerator Save()
{
while (true)
{
Debug.Log("setting playerperfab ....");
yield return new WaitForSeconds(5f);
ApplicationModel.RestorePerfab();
}
}
public static void RestorePerfab(){
PlayerPerfabs.SetInt("point", point);
}
private void Start(){
StartCoroutine(Save());
}
}
但是根据控制台日志,协程从未执行(因为从未打印日志)。
也许是因为我没有将此脚本附加到游戏对象,但是一旦我将其附加到游戏对象,那么当场景发生变化或该游戏对象被破坏时,定期保存就会结束,对吧?那么如何做到这一点呢?
最佳答案
如果您希望它工作,您需要创建一个 GameObject
,然后将此脚本附加到它。如果您要更改场景并希望它继续工作,您可以在该 GameObject
上调用 DontDestroyOnLoad
,并且当您切换场景时它不会被破坏。
关于c# - Unity定期设置PlayerPrefs数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43359096/