Unity study notes InputManager judges the click behavior of physical buttons

question

In Unity's old input system InputManager, only three interfaces, Input.GetButton(), GetButtonDown(), and GetButtonUp(), are provided to judge the button state. Lack of judgment on Click behavior.

Solution

Set a threshold as the judgment time of the click behavior,
and rely on the timing between GetButtonDown and GetButtonUp to make judgments

In Update:
insert image description here

private static bool isComfirmButtonClicked;
    public static bool IsComfirmButtonClicked
    {
    
    
        get => isComfirmButtonClicked;
    }
    
    [SerializeField] private float clickThreshold = 0.2f;
    private float timer;
    private bool hasButtonDown;

    private const string SUBMITBUTTON = "Submit";
    private void Update()
    {
    
    
        if (Input.GetButtonDown(SUBMITBUTTON))
        {
    
    
            hasButtonDown = true;
            timer = 0;
        }

        if (!hasButtonDown)
        {
    
    
            isComfirmButtonClicked = false;
            return;
        }
        else
        {
    
    
            timer += Time.deltaTime;
            if (timer >= clickThreshold)
            {
    
    
                isComfirmButtonClicked = false;
            }
            else
            {
    
    
                if (Input.GetButtonUp(SUBMITBUTTON))
                {
    
    
                    hasButtonDown = false;
                    isComfirmButtonClicked = true;
                }
            }
        }
    }

Guess you like

Origin blog.csdn.net/weixin_42358083/article/details/123592039