Skip to content

Input Manager

Ilan edited this page Apr 8, 2024 · 1 revision

Explanation

Unity provides a modern way to listen to the inputs of the player. This is called the New Input System. This wiki is not here to explain how this feature works (if needed, there are plenty resources online: guides, youtube videos, articles...) but how to use it correctly in this project.

As mentioned in the previous page (Event Manager), we want to avoid DEATH. In a game, many scripts want to react to an user input. Hence, many scripts would like to reference the input manager. This is something we cannot allow as we want these scripts to work without it and be ready when it is there.

The Input Manager is a root dependency, similar to the Event Manager one. There can be only one active at the same time and it will last until the game stops. Its goal is to listen to the Unity PlayerInputs script inputs event and retransmit them with the Event Manager system. Hence, the other scripts simply need to listen to the event created for this occasion and not reference anything else.

Implementation

After creating your event through the New Input System, you will need to modify the Input Manager script and add a new method to the class named On[Action Name] the Action Name must be exactly like you did in the interface.

Hence, if I have an input called Reload, associated with R. I would like to create a method in InputManager with the following prototype:

 private void OnReload(InputValue inputValue);

Normally, the PlayerInput will automatically call a function named with the following pattern. So make sure the method is correctly named otherwise it won't work.

Then, you simply need to retransmit the event. If the event is basic, you just need to know when the key is pressed for the first time (not held), you just have to have this design:

private void OnReload(InputValue inputValue)
{
    EventManager.TriggerEvent("OnReload");
}

To keep things simple, we didn't use a constant for the event name, but make sure to do so as said in the previous page (Event Manager)

If you want to do an action toggle or while the key is pressed, we want to use a boolean! (be sure to set the input action as "Press And Release" for the while)

private void OnFreeLook(InputValue inputValue)
{
    EventManager.TriggerEvent(Constants.TypedEvents.Inputs.OnFreeLook, inputValue.isPressed); // we can know if we should toggle or start/stop
}

Hence later, we can listen to the input with

// MyMonoBehaviour.cs
private void OnEnable()
{
    EventManager.AddListener(Constants.TypedEvents.Inputs.OnFreeLook, MyListener);
}

private void OnDisable()
{
    EventManager.RemoveListener(Constants.TypedEvents.Inputs.OnFreeLook, MyListener);
}

private void MyListener(object data)
{
    if (data is bool isPressed)
    {
        // do something with isPressed
    }
}

Previous     •     Home     •     Next
Clone this wiki locally