Skip to content

Receive keyboard input even when Unity.app is in the background with no focus on macOS.

License

Notifications You must be signed in to change notification settings

fuziki/UnityAppEventMonitor

Repository files navigation

UnityAppEventMonitor

Platform Unity Xode

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.

Requirements

Unity

  • Unity 2020.X
  • Unity 2021.X
  • Unity 2022.X
  • Unity 2022.2+ (Apple Silicon)

Platforms

  • macOS 12+ (Apple Silicon and Intel)

Installation

Unity Pakcage Manager (UPM)

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 Source

Copy and paste Examples/UnityAppEventMonitor/Assets/Plugins/AppEventMonitor into your Unity project.

Privacy Settings

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)

Feature

Keyboard Events

  • key down
  • key up
  • modifier key

Mouse Events

  • left mouse down
  • left mouse dragged
  • left mouse up
  • right mouse down
  • right mouse dragged
  • right mouse up
  • mouse moved
  • scroll wheel

Touch Events

  • begin gesture
  • end gesture

Usage

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}");
    }
}

Example Projects

About

Receive keyboard input even when Unity.app is in the background with no focus on macOS.

Topics

Resources

License

Code of conduct

Stars

Watchers

Forks