-
Notifications
You must be signed in to change notification settings - Fork 317
/
Copy pathRebindActionUI.cs
450 lines (390 loc) · 16.3 KB
/
RebindActionUI.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
using System;
using System.Collections.Generic;
using UnityEngine.Events;
using UnityEngine.UI;
////TODO: localization support
////TODO: deal with composites that have parts bound in different control schemes
namespace UnityEngine.InputSystem.Samples.RebindUI
{
/// <summary>
/// A reusable component with a self-contained UI for rebinding a single action.
/// </summary>
public class RebindActionUI : MonoBehaviour
{
/// <summary>
/// Reference to the action that is to be rebound.
/// </summary>
public InputActionReference actionReference
{
get => m_Action;
set
{
m_Action = value;
UpdateActionLabel();
UpdateBindingDisplay();
}
}
/// <summary>
/// ID (in string form) of the binding that is to be rebound on the action.
/// </summary>
/// <seealso cref="InputBinding.id"/>
public string bindingId
{
get => m_BindingId;
set
{
m_BindingId = value;
UpdateBindingDisplay();
}
}
public InputBinding.DisplayStringOptions displayStringOptions
{
get => m_DisplayStringOptions;
set
{
m_DisplayStringOptions = value;
UpdateBindingDisplay();
}
}
/// <summary>
/// Text component that receives the name of the action. Optional.
/// </summary>
public Text actionLabel
{
get => m_ActionLabel;
set
{
m_ActionLabel = value;
UpdateActionLabel();
}
}
/// <summary>
/// Text component that receives the display string of the binding. Can be <c>null</c> in which
/// case the component entirely relies on <see cref="updateBindingUIEvent"/>.
/// </summary>
public Text bindingText
{
get => m_BindingText;
set
{
m_BindingText = value;
UpdateBindingDisplay();
}
}
/// <summary>
/// Optional text component that receives a text prompt when waiting for a control to be actuated.
/// </summary>
/// <seealso cref="startRebindEvent"/>
/// <seealso cref="rebindOverlay"/>
public Text rebindPrompt
{
get => m_RebindText;
set => m_RebindText = value;
}
/// <summary>
/// Optional UI that is activated when an interactive rebind is started and deactivated when the rebind
/// is finished. This is normally used to display an overlay over the current UI while the system is
/// waiting for a control to be actuated.
/// </summary>
/// <remarks>
/// If neither <see cref="rebindPrompt"/> nor <c>rebindOverlay</c> is set, the component will temporarily
/// replaced the <see cref="bindingText"/> (if not <c>null</c>) with <c>"Waiting..."</c>.
/// </remarks>
/// <seealso cref="startRebindEvent"/>
/// <seealso cref="rebindPrompt"/>
public GameObject rebindOverlay
{
get => m_RebindOverlay;
set => m_RebindOverlay = value;
}
/// <summary>
/// Event that is triggered every time the UI updates to reflect the current binding.
/// This can be used to tie custom visualizations to bindings.
/// </summary>
public UpdateBindingUIEvent updateBindingUIEvent
{
get
{
if (m_UpdateBindingUIEvent == null)
m_UpdateBindingUIEvent = new UpdateBindingUIEvent();
return m_UpdateBindingUIEvent;
}
}
/// <summary>
/// Event that is triggered when an interactive rebind is started on the action.
/// </summary>
public InteractiveRebindEvent startRebindEvent
{
get
{
if (m_RebindStartEvent == null)
m_RebindStartEvent = new InteractiveRebindEvent();
return m_RebindStartEvent;
}
}
/// <summary>
/// Event that is triggered when an interactive rebind has been completed or canceled.
/// </summary>
public InteractiveRebindEvent stopRebindEvent
{
get
{
if (m_RebindStopEvent == null)
m_RebindStopEvent = new InteractiveRebindEvent();
return m_RebindStopEvent;
}
}
/// <summary>
/// When an interactive rebind is in progress, this is the rebind operation controller.
/// Otherwise, it is <c>null</c>.
/// </summary>
public InputActionRebindingExtensions.RebindingOperation ongoingRebind => m_RebindOperation;
/// <summary>
/// Return the action and binding index for the binding that is targeted by the component
/// according to
/// </summary>
/// <param name="action"></param>
/// <param name="bindingIndex"></param>
/// <returns></returns>
public bool ResolveActionAndBinding(out InputAction action, out int bindingIndex)
{
bindingIndex = -1;
action = m_Action?.action;
if (action == null)
return false;
if (string.IsNullOrEmpty(m_BindingId))
return false;
// Look up binding index.
var bindingId = new Guid(m_BindingId);
bindingIndex = action.bindings.IndexOf(x => x.id == bindingId);
if (bindingIndex == -1)
{
Debug.LogError($"Cannot find binding with ID '{bindingId}' on '{action}'", this);
return false;
}
return true;
}
/// <summary>
/// Trigger a refresh of the currently displayed binding.
/// </summary>
public void UpdateBindingDisplay()
{
var displayString = string.Empty;
var deviceLayoutName = default(string);
var controlPath = default(string);
// Get display string from action.
var action = m_Action?.action;
if (action != null)
{
var bindingIndex = action.bindings.IndexOf(x => x.id.ToString() == m_BindingId);
if (bindingIndex != -1)
displayString = action.GetBindingDisplayString(bindingIndex, out deviceLayoutName, out controlPath, displayStringOptions);
}
// Set on label (if any).
if (m_BindingText != null)
m_BindingText.text = displayString;
// Give listeners a chance to configure UI in response.
m_UpdateBindingUIEvent?.Invoke(this, displayString, deviceLayoutName, controlPath);
}
/// <summary>
/// Remove currently applied binding overrides.
/// </summary>
public void ResetToDefault()
{
if (!ResolveActionAndBinding(out var action, out var bindingIndex))
return;
if (action.bindings[bindingIndex].isComposite)
{
// It's a composite. Remove overrides from part bindings.
for (var i = bindingIndex + 1; i < action.bindings.Count && action.bindings[i].isPartOfComposite; ++i)
action.RemoveBindingOverride(i);
}
else
{
action.RemoveBindingOverride(bindingIndex);
}
UpdateBindingDisplay();
}
/// <summary>
/// Initiate an interactive rebind that lets the player actuate a control to choose a new binding
/// for the action.
/// </summary>
public void StartInteractiveRebind()
{
if (!ResolveActionAndBinding(out var action, out var bindingIndex))
return;
// If the binding is a composite, we need to rebind each part in turn.
if (action.bindings[bindingIndex].isComposite)
{
var firstPartIndex = bindingIndex + 1;
if (firstPartIndex < action.bindings.Count && action.bindings[firstPartIndex].isPartOfComposite)
PerformInteractiveRebind(action, firstPartIndex, allCompositeParts: true);
}
else
{
PerformInteractiveRebind(action, bindingIndex);
}
}
private void PerformInteractiveRebind(InputAction action, int bindingIndex, bool allCompositeParts = false)
{
m_RebindOperation?.Cancel(); // Will null out m_RebindOperation.
void CleanUp()
{
m_RebindOperation?.Dispose();
m_RebindOperation = null;
action.Enable();
}
//Fixes the "InvalidOperationException: Cannot rebind action x while it is enabled" error
action.Disable();
// Configure the rebind.
m_RebindOperation = action.PerformInteractiveRebinding(bindingIndex)
.OnCancel(
operation =>
{
m_RebindStopEvent?.Invoke(this, operation);
if (m_RebindOverlay != null)
m_RebindOverlay.SetActive(false);
UpdateBindingDisplay();
CleanUp();
})
.OnComplete(
operation =>
{
if (m_RebindOverlay != null)
m_RebindOverlay.SetActive(false);
m_RebindStopEvent?.Invoke(this, operation);
UpdateBindingDisplay();
CleanUp();
// If there's more composite parts we should bind, initiate a rebind
// for the next part.
if (allCompositeParts)
{
var nextBindingIndex = bindingIndex + 1;
if (nextBindingIndex < action.bindings.Count && action.bindings[nextBindingIndex].isPartOfComposite)
PerformInteractiveRebind(action, nextBindingIndex, true);
}
});
// If it's a part binding, show the name of the part in the UI.
var partName = default(string);
if (action.bindings[bindingIndex].isPartOfComposite)
partName = $"Binding '{action.bindings[bindingIndex].name}'. ";
// Bring up rebind overlay, if we have one.
m_RebindOverlay?.SetActive(true);
if (m_RebindText != null)
{
var text = !string.IsNullOrEmpty(m_RebindOperation.expectedControlType)
? $"{partName}Waiting for {m_RebindOperation.expectedControlType} input..."
: $"{partName}Waiting for input...";
m_RebindText.text = text;
}
// If we have no rebind overlay and no callback but we have a binding text label,
// temporarily set the binding text label to "<Waiting>".
if (m_RebindOverlay == null && m_RebindText == null && m_RebindStartEvent == null && m_BindingText != null)
m_BindingText.text = "<Waiting...>";
// Give listeners a chance to act on the rebind starting.
m_RebindStartEvent?.Invoke(this, m_RebindOperation);
m_RebindOperation.Start();
}
protected void OnEnable()
{
if (s_RebindActionUIs == null)
s_RebindActionUIs = new List<RebindActionUI>();
s_RebindActionUIs.Add(this);
if (s_RebindActionUIs.Count == 1)
InputSystem.onActionChange += OnActionChange;
}
protected void OnDisable()
{
m_RebindOperation?.Dispose();
m_RebindOperation = null;
s_RebindActionUIs.Remove(this);
if (s_RebindActionUIs.Count == 0)
{
s_RebindActionUIs = null;
InputSystem.onActionChange -= OnActionChange;
}
}
// When the action system re-resolves bindings, we want to update our UI in response. While this will
// also trigger from changes we made ourselves, it ensures that we react to changes made elsewhere. If
// the user changes keyboard layout, for example, we will get a BoundControlsChanged notification and
// will update our UI to reflect the current keyboard layout.
private static void OnActionChange(object obj, InputActionChange change)
{
if (change != InputActionChange.BoundControlsChanged)
return;
var action = obj as InputAction;
var actionMap = action?.actionMap ?? obj as InputActionMap;
var actionAsset = actionMap?.asset ?? obj as InputActionAsset;
for (var i = 0; i < s_RebindActionUIs.Count; ++i)
{
var component = s_RebindActionUIs[i];
var referencedAction = component.actionReference?.action;
if (referencedAction == null)
continue;
if (referencedAction == action ||
referencedAction.actionMap == actionMap ||
referencedAction.actionMap?.asset == actionAsset)
component.UpdateBindingDisplay();
}
}
[Tooltip("Reference to action that is to be rebound from the UI.")]
[SerializeField]
private InputActionReference m_Action;
[SerializeField]
private string m_BindingId;
[SerializeField]
private InputBinding.DisplayStringOptions m_DisplayStringOptions;
[Tooltip("Text label that will receive the name of the action. Optional. Set to None to have the "
+ "rebind UI not show a label for the action.")]
[SerializeField]
private Text m_ActionLabel;
[Tooltip("Text label that will receive the current, formatted binding string.")]
[SerializeField]
private Text m_BindingText;
[Tooltip("Optional UI that will be shown while a rebind is in progress.")]
[SerializeField]
private GameObject m_RebindOverlay;
[Tooltip("Optional text label that will be updated with prompt for user input.")]
[SerializeField]
private Text m_RebindText;
[Tooltip("Event that is triggered when the way the binding is display should be updated. This allows displaying "
+ "bindings in custom ways, e.g. using images instead of text.")]
[SerializeField]
private UpdateBindingUIEvent m_UpdateBindingUIEvent;
[Tooltip("Event that is triggered when an interactive rebind is being initiated. This can be used, for example, "
+ "to implement custom UI behavior while a rebind is in progress. It can also be used to further "
+ "customize the rebind.")]
[SerializeField]
private InteractiveRebindEvent m_RebindStartEvent;
[Tooltip("Event that is triggered when an interactive rebind is complete or has been aborted.")]
[SerializeField]
private InteractiveRebindEvent m_RebindStopEvent;
private InputActionRebindingExtensions.RebindingOperation m_RebindOperation;
private static List<RebindActionUI> s_RebindActionUIs;
// We want the label for the action name to update in edit mode, too, so
// we kick that off from here.
#if UNITY_EDITOR
protected void OnValidate()
{
UpdateActionLabel();
UpdateBindingDisplay();
}
#endif
private void UpdateActionLabel()
{
if (m_ActionLabel != null)
{
var action = m_Action?.action;
m_ActionLabel.text = action != null ? action.name : string.Empty;
}
}
[Serializable]
public class UpdateBindingUIEvent : UnityEvent<RebindActionUI, string, string, string>
{
}
[Serializable]
public class InteractiveRebindEvent : UnityEvent<RebindActionUI, InputActionRebindingExtensions.RebindingOperation>
{
}
}
}