简体   繁体   English

在Unity游戏引擎中打开框后的C#倒计时

[英]C# countdown after opening box in the Unity game engine

I need to access the PC or Android system time at opening a box and save it, then start counting down 5 minutes from that time. 我需要在打开包装盒并保存它之后访问PC或Android系统时间,然后从该时间开始倒数5分钟。 When 5 minutes pass, re-enable the button to open the box. 5分钟后,重新启用按钮以打开该框。 I've tried many approaches but all lead to a dead end. 我已经尝试了许多方法,但是所有方法都会导致死胡同。

public class Test : MonoBehaviour
{
    public Button boxButton;
    long previousOpenedBox;

    private void Update()
    {
        if (!boxButton.IsInteractable())
        {
            long diff = (DateTime.Now.Ticks - previousOpenedBox);
            //start counting down the time to re-enable the button.
        }
    }

    public void BoxClicked()
    {
        long previousOpenedBox = DateTime.Now.Ticks;
        boxButton.interactable = false;
    }
}

I don't know why you are implementing your opening logics when you update the box, you should put them in the BoxClicked method instead. 我不知道为什么在更新框时为什么要实现打开逻辑,应该将它们放在BoxClicked方法中。 This minimal example shows how to deal with a blocking delay and should point you to the right path. 这个最小的示例显示了如何处理阻塞延迟,并应指出正确的路径。

public class Test : MonoBehaviour
{
    private DateTime m_LastOpening;
    public Button m_BoxButton;

    public void BoxClicked()
    {
        DateTime now = DateTime.Now;

        // 5 minutes elapsed, you can open the box
        if ((now - m_LastOpening).TotalMinutes > 5)
        {
            m_LastOpening = now;
            m_BoxButton.interactable = false;
        }
        else // otherwise you have to wait
        {
            // ...
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM