【问题标题】:Unity set PlayerPrefs data regularlyunity 定期设置 PlayerPrefs 数据
【发布时间】:2017-04-12 02:17:39
【问题描述】:

我正在使用 PlayerPerfabs 来存储玩家数据,例如玩家解锁了哪个级别以及在游戏过程中获得的分数,并且我希望在游戏过程中定期(例如每 5 秒)更新 PlayerPerfabs 数据,所以我创建了一个名为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());
    }

}

但是根据控制台日志从来没有执行过协程(因为日志从来没有打印出来)。

也许是因为我没有将此脚本附加到游戏对象,但是一旦我将其附加到游戏对象,那么当场景更改或该游戏对象被破坏时,定期保存将结束,对吗?那么如何做到这一点呢?

【问题讨论】:

    标签: c# unity3d coroutine


    【解决方案1】:

    您需要创建一个GameObject,然后将此脚本附加到它,如果您希望它工作。如果您正在更改场景并希望它继续工作,您可以在该GameObject 上调用DontDestroyOnLoad,并且在您切换场景时它不会被破坏。

    【讨论】:

    • 我认为使用单例会更好。由于数据链deos不需要复制。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-18
    相关资源
    最近更新 更多