-
Notifications
You must be signed in to change notification settings - Fork 2
/
DeviceConnectionHandler.cs
66 lines (55 loc) · 2.24 KB
/
DeviceConnectionHandler.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
using System;
using System.Collections.Generic;
using UnityEngine.InputSystem;
/// <summary>
/// Example for how to properly handle the container devices for VariantDevices.
/// </summary>
public static class DeviceConnectionHandler
{
public static event Action<InputDevice> DeviceAdded;
public static event Action<InputDevice> DeviceRemoved;
private static readonly HashSet<InputDevice> _disabledDevices = new HashSet<InputDevice>();
public static void Initialize()
{
InputSystem.onDeviceChange += OnDeviceChange;
}
private static void OnDeviceChange(InputDevice device, InputDeviceChange change)
{
switch (change)
{
case InputDeviceChange.Added:
// Ignore if the device was disabled before being added
// Necessary for ignoring VariantDevices correctly, without this they
// will be exposed to the rest of the application for a brief moment.
if (!device.enabled)
{
_disabledDevices.Add(device);
return;
}
DeviceAdded?.Invoke(device);
break;
case InputDeviceChange.Removed:
// Ignore if the device was disabled before being removed,
// as DeviceRemoved will have already been fired for it.
if (_disabledDevices.Remove(device))
return;
DeviceRemoved?.Invoke(device);
break;
// case InputDeviceChange.Reconnected: // Fired alongside Added, not needed
case InputDeviceChange.Enabled:
// Ignore if the device was already enabled.
if (!_disabledDevices.Remove(device))
return;
DeviceAdded?.Invoke(device);
break;
// case InputDeviceChange.Disconnected: // Fired alongside Removed, not needed
case InputDeviceChange.Disabled:
// Ignore if the device was already disabled.
if (_disabledDevices.Contains(device))
return;
_disabledDevices.Add(device);
DeviceRemoved?.Invoke(device);
break;
}
}
}