Checking for input once per frame using GetButton()

Hi everyone!

So, I’m still somewhat new to this so please bear with me.

I have a mouse to world raycast script going which looks like this:

RaycastHit _hit;
Ray _ray = camera.ScreenPointToRay(Input.mousePosition);
Debug.DrawRay(_ray.origin, _ray.direction * 50, Color.blue);

if (Input.GetButton("Fire1"))
{
[INDENT]if (Physics.Raycast(_ray, out _hit))[/INDENT]
            {
                Transform _object = _hit.transform;
                Debug.Log(_object);
                var _engine = _object.GetComponent<EngineControl>();
                _engine.isOn = !_engine.isOn;
            }
}

What it does (for now) is it shoots out a raycast, and flips a bool. However, I’m using if (Input.GetButton("Fire1")) and not GetButtonDown(). The reason behind this was there is a chance that the click might be between frames (not sure actually) in which case nothing would happen.
However, if I use GetButton() by itself, it will register the click 3, sometimes 4 times, even though I only need it once. So, I figured I should check if there was input in the previous frame. Thing is, I’m at a loss as to how I should make that check. I know that I should check for it in the same line as GetButton() but after that, I’m not sure.

Thanks for the help!

No, use GetButtonDown. You can’t have clicks between frames. (But don’t use FixedUpdate, because you can miss frames with that.)

–Eric

1 Like