-
Notifications
You must be signed in to change notification settings - Fork 102
/
Copy pathCursorUnlocker.cs
98 lines (80 loc) · 3.32 KB
/
CursorUnlocker.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
using System;
using System.Reflection;
using RuntimeUnityEditor.Core.Utils.Abstractions;
using UnityEngine;
#pragma warning disable CS1591
namespace RuntimeUnityEditor.Core
{
/// <summary>
/// Feature that forces the mouse cursor to stay unlocked/visible. Might cause issues with some games, especially FPSes.
/// </summary>
public sealed class CursorUnlocker : FeatureBase<CursorUnlocker>
{
private bool _obsoleteCursor;
private PropertyInfo _curLockState;
private PropertyInfo _curVisible;
private int _previousCursorLockState;
private bool _previousCursorVisible;
protected override void Initialize(InitSettings initSettings)
{
// Reflection for compatibility with Unity 4.x
var tCursor = typeof(Cursor);
_curLockState = tCursor.GetProperty("lockState", BindingFlags.Static | BindingFlags.Public);
_curVisible = tCursor.GetProperty("visible", BindingFlags.Static | BindingFlags.Public);
if (_curLockState == null || _curVisible == null)
{
_obsoleteCursor = true;
_curLockState = typeof(Screen).GetProperty("lockCursor", BindingFlags.Static | BindingFlags.Public);
_curVisible = typeof(Screen).GetProperty("showCursor", BindingFlags.Static | BindingFlags.Public);
if (_curLockState == null || _curVisible == null)
throw new InvalidOperationException("Unsupported Cursor class");
}
DisplayName = "Unlock cursor";
Enabled = true;
DisplayType = FeatureDisplayType.Hidden;
}
protected override void Update()
{
if (_obsoleteCursor)
_curLockState.SetValue(null, false, null);
else
_curLockState.SetValue(null, 0, null);
_curVisible.SetValue(null, true, null);
}
protected override void LateUpdate()
{
if (_obsoleteCursor)
_curLockState.SetValue(null, false, null);
else
_curLockState.SetValue(null, 0, null);
_curVisible.SetValue(null, true, null);
}
protected override void OnGUI()
{
if (_obsoleteCursor)
_curLockState.SetValue(null, false, null);
else
_curLockState.SetValue(null, 0, null);
_curVisible.SetValue(null, true, null);
}
protected override void VisibleChanged(bool visible)
{
if (visible)
{
_previousCursorLockState = _obsoleteCursor ? Convert.ToInt32((bool)_curLockState.GetValue(null, null)) : (int)_curLockState.GetValue(null, null);
_previousCursorVisible = (bool)_curVisible.GetValue(null, null);
}
else
{
if (!_previousCursorVisible || _previousCursorLockState != 0)
{
if (_obsoleteCursor)
_curLockState.SetValue(null, Convert.ToBoolean(_previousCursorLockState), null);
else
_curLockState.SetValue(null, _previousCursorLockState, null);
_curVisible.SetValue(null, _previousCursorVisible, null);
}
}
}
}
}