重新打开游戏时如何查看时间是否过去? [英] How to check if time passed or not when game re-opened?

查看:52
本文介绍了重新打开游戏时如何查看时间是否过去?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

协程在"tebs"变量在游戏中获得某些值时运行.并且,当它起作用时,它将 timeScale 设置为零并等待一会儿,然后游戏继续继续.

The coroutine runs when "tebs" variable gets some value through the game. And while it works, it sets timeScale to zero and waiting for a while and then the game keeps continue.

问题是我想在游戏关闭并重新打开时检查游戏的实时/本地时间,并比较它们以检查时间是否过去,以便协程保持运行或结束.

The problem is that i want to game checks the real time/local time when the game closed and re-opened and compare them to check if the time passed or not, so coroutine keeps running or ends.

IEnumerator TEBSWait()
    {
        //INK PLUGIN VARIABLE THAT DETERMINES THE SECONDS TO WAIT
        int tebs = (int)_inkStory.variablesState["TEBS"];

        //SAVE GAME
        Debug.Log("tebsSaved");
        var savedState = _inkStory.state.ToJson();
        PlayerPrefs.SetString("tebsSaved", savedState);

        //STOP TIME & WAIT FOR A WHILE 
        Time.timeScale = 0;
        yield return new WaitForSecondsRealtime(tebs * 60); 
        Time.timeScale = 1;

        PlayerPrefs.DeleteKey("tebsSaved");
    }

谢谢.

推荐答案

当用户失去焦点或退出应用程序时,请节省当前时间.当用户返回负载时,将前一时间与当前时间进行比较.这样做会给您带来时间上的差异.

When the user loses focus or quits the app, save the current time. When the user returns load the previous time and compare it with the current time. Doing this will give you the difference in time.

在我的示例中,我将刻度保存到PlayerPrefs.请记住, DateTime.UtcNow.Ticks 是一个 long ,并且PlayerPrefs只能将 int 用作数值,因此我必须将其存储作为 string .

In my example, I save ticks to the PlayerPrefs. Keep in mind that DateTime.UtcNow.Ticks is a long, and PlayerPrefs can only take int for numeric values, so I had to store it as a string.

void Awake()
{
    Load();
}

void OnApplicationQuit()
{
    Save();
}

void OnApplicationFocus(bool hasFocus)
{
    if (hasFocus) Load();
    else Save();
}

void Load()
{
    long nowTicks = DateTime.UtcNow.Ticks;
    long prevTicks = nowTicks;

    string prevTicksString = PlayerPrefs.GetString("ticks", string.Empty);
    if (!string.IsNullOrEmpty(prevTicksString)) prevTicks = long.Parse(prevTicksString);

    double secondsPassed = TimeSpan.FromTicks(nowTicks - prevTicks).TotalSeconds;

    Debug.Log(secondsPassed);
}

void Save()
{
    PlayerPrefs.SetString("ticks", DateTime.UtcNow.Ticks.ToString());
    PlayerPrefs.Save();
}

这篇关于重新打开游戏时如何查看时间是否过去?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆