/UnityRawInput

Windows Raw Input wrapper for Unity game engine

Primary LanguageC#MIT LicenseMIT

Download package

For Unity 2017.4 and later: UnityRawInput.unitypackage.

Please be aware that you don't need to clone the whole repository in order to use the extension in your project. Either download package from the link above or extract Assets/UnityRawInput folder from the repository project – it contains all the required assets; other stuff is just for testing purposes.

Description

Wrapper over Windows Raw Input API to hook for the native input events. Allows to receive input events even when the Unity application is in background (not in focus).

Will only work on Windows platform.

Only keyboard input is currently supported.

Usage

Include package namespace.

using UnityRawInput;

Initialize the input service to start processing native input messages.

RawKeyInput.Start();

Optinally, you can specify whether input messages should be handled when the application is not in focus (disabled by default).

var workInBackground = true;
RawKeyInput.Start(workInBackground);

Add listeners for the input events.

RawKeyInput.OnKeyUp += HandleKeyUp;
RawKeyInput.OnKeyDown += HandleKeyDown;

private void HandleKeyUp (RawKey key) { ... }
private void HandleKeyDown (RawKey key) { ... }

You can also check whether specific key is currently pressed.

if (RawKeyInput.IsKeyDown(key)) { ... }

You can stop the service at any time.

RawKeyInput.Stop();

Don't forget to remove listeners when you no longer need them.

private void OnDisable ()
{
    RawKeyInput.OnKeyUp -= HandleKeyUp;
    RawKeyInput.OnKeyDown -= HandleKeyDown;
}