【问题标题】:How to delay the else statement without coroutine in unity c#?如何在 unity c# 中延迟没有协程的 else 语句?
【发布时间】:2023-02-11 14:55:03
【问题描述】:

我的游戏有一个操纵杆显示图片。目前,当玩家触摸屏幕时,图像会消失,而当玩家没有触摸屏幕时,它会重新出现。我是用 if else 语句写的。

if (indicator.inputIndicator.x != 0)
{
    joystick.SetActive(false);
}
else
{
    joystick.SetActive(true);
}

问题是,我希望图像在 2 秒后重新出现。我想延迟“else”,但我不想使用协程。我希望“else”在玩家将手从屏幕上移开 2 秒后工作,但我不知道该怎么做。任何帮助都会很棒。

【问题讨论】:

    标签: c# unity3d if-statement


    【解决方案1】:

    设置计时器是您必须在 Unity 中解决的一个非常常见的问题。一种基本方法是在每次更新时添加一个变量 Time.deltaTime。这样你就可以知道自满足某些条件以来已经过了多长时间。

    满足条件的每个更新迭代,将 Time.deltaTime 添加到变量中。如果在某个时候条件失败,请将变量重置为 0。然后您可以将 joystick.SetActive() 调用基于变量的值。

    例如,您的脚本可能会变成:

    float thresholdTimeToShowPrompt = 2;
    
    // By starting at the threshold, the image is hidden at the start until a touch
    float timeSincePlayerTouch = 2;
    
    void Update()
    {
        // Rather than calling SetActive directly, just update the timer
        if (indicator.inputIndicator.x != 0)
        {
            timeSincePlayerTouch = 0;
        }
        else
        {
            timeSincePlayerTouch += Time.deltaTime;
        }
        
        // Now we can base visibility on the time since the last user touch
        bool shouldShowIcon = timeSincePlayerTouch >= thresholdTimeToShowPrompt;
        
        // Only call SetActive when needed, in case of overhead
        if (shouldShowIcon && !joystick.activeSelf)
        {
            joystick.SetActive(true);
        }
        else if (!shouldShowIcon && joystick.activeSelf)
        {
            joystick.SetActive(false);
        }
    }
    

    【讨论】:

    • 太好了,谢谢你的帮助。它运作良好,但问题是游戏开始时图像也会在延迟之后出现。
    • @icarus 我明白你的意思了——从已经隐藏的图像开始,你可以在阈值时间初始化计时器变量。我已经相应地更新了我的答案。如果您还有其他问题,请告诉我!
    • 哦,这是有道理的,我全神贯注于其他事情。它的工作就像我想要的那样。谢谢你的帮助,我很感激。
    猜你喜欢
    • 2023-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-10
    • 1970-01-01
    • 1970-01-01
    • 2011-07-20
    相关资源
    最近更新 更多