Unity Native Plugin for NSEvent.addGlobalMonitorForEvents.
Receive keyboard input even when Unity.app is in the background with no focus.
This Plugin works only on macOS.
This GIF shows that unity can detect keys entered into TextEdit.
- Unity 2020.X
- Unity 2021.X
- Unity 2022.X
- Unity 2022.2+ (Apple Silicon)
- macOS 12+ (Apple Silicon and Intel)
Select "Add package from git URL" in the Unity Package Manager and enter the following path. https://github.com/fuziki/UnityAppEventMonitor.git?path=Examples/UnityAppEventMonitor/Assets/Plugins/AppEventMonitor
Copy and paste Examples/UnityAppEventMonitor/Assets/Plugins/AppEventMonitor into your Unity project.
To allow monitoring of keyboard input in the background, you need to add Unity to Accessibility.
Open System Preferences
> Security & Privacy
> Privacy
> Accessibility
and add Unity.app
.
(And Unity Hub.app
if you use)
- key down
- key up
- modifier key
- left mouse down
- left mouse dragged
- left mouse up
- right mouse down
- right mouse dragged
- right mouse up
- mouse moved
- scroll wheel
- begin gesture
- end gesture
Include package.
using AppEventMonitor;
Add action.
private void OnKeyDown(string key)
{
Debug.Log($"OnKeyDown: {key}");
}
AppEventMonitorManager.OnKeyDown += OnKeyDown;
Start monitoring.
AppEventMonitorManager.Start();
Stop monitoring.
AppEventMonitorManager.Stop();
Example
using UnityEngine;
using AppEventMonitor;
public class Cube : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
AppEventMonitorManager.OnKeyDown += OnKeyDown;
Debug.Log("Start!!");
AppEventMonitorManager.Start();
}
void OnDestroy()
{
Debug.Log("Stop!!");
AppEventMonitorManager.Stop();
}
private void OnKeyDown(string key)
{
Debug.Log($"OnKeyDown: {key}");
}
}