Trying to replicate Input.GetButtonDown() for game controller input. Need help refactoring...

Since Unity’s Input manager is a little rough around the edges I thought I’d write my own. I’m working on a gamepad/controller script that

just like Input.GetButtonDown().

It functions fine, but I can’t help but think there’s a better way of doing it.
With this method, I have to create 2 public static variables just for one trigger.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public static class InputManager {

// The variable names have lowercase L's in the script, but on the web it looks like iMessage,
// which confuses readability; L refering to the left trigger as opposed to right.
    public static bool LMessage = false;
    public static bool LMessageSent = false;

    public static bool LeftTriggerDown(float triggerValue = .9f, float releaseValue = .0001f)
    {
        if (Input.GetAxis("Left Trigger") > triggerValue && messageSent == false)
        {
            LMessage = true;
            LMessageSent = true;
            return LMessage;
        }
        else if (Input.GetAxis("Left Trigger") < releaseValue)
        {
            LMessage = false;
            LMessageSent = false;
            return LMessage;
        }
        else { return false; }
    }

Assuming this function is only going to be called in the Update() function, is there another way of organizing this code? Preferably using local variables? I don’t like having those public-statics…

Thanks in advance!

Generally, if you have:

 bool buttonIsDown;
 bool prevFrameButtonIsDown;

Then the expression for “was it pressed this frame” is simply:

 bool pressedThisFrame = buttonIsDown && !prevFrameButtonIsDown;

Conversely, the expression for “was it released this frame” is essentially the reverse:

 bool releasedThisFrame = prevFrameButtonIsDown && !buttonIsDown;

Wrap those expressions up however you like, but ONLY “age” the buttonIsDown to prevFrameButtonIsDown ONCE per frame, and be sure it is done AFTER all other users have consumed the data. (or make sure it’s done before).

And how does one check to see if a button was down in the previous frame?

As @Kurt-Dekker said, you do this by copying bottonIsDown into prevFrameButtonIsDown once per frame. For example, you might do this in LateUpdate:

void LateUpdate() {
    prevFrameButtonIsDown = buttonIsDown;
}

…and then just note that you can’t reliably use this in other scripts’ LateUpdate methods.

1 Like

I used this after finding the same problem for pausing. Thanks for the help!

 pressedThisFrame = pauseButton && !pressedLastFrame;
       
        if (pressedThisFrame)
        {
            if (!GameIsPaused)
            {
                Pause();
            }
            else if (GameIsPaused)
            {
                Resume();
            }
        }

        pressedLastFrame = pauseButton;