summaryrefslogtreecommitdiff
path: root/Assets/Samples/OpenXR Plugin/1.14.3/Controller/Scripts/ActionToControl.cs
blob: fa875785579d3bf9f87ef2f83a7cf0308dcf42be (plain)
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
using System.Collections;
using UnityEngine.InputSystem;
using UnityEngine.UI;
using UnityEngine.XR.OpenXR.Input;

namespace UnityEngine.XR.OpenXR.Samples.ControllerSample
{
    public class ActionToControl : MonoBehaviour
    {
        [Tooltip("Action Reference that represents the control")]
        [SerializeField] private InputActionReference _actionReference = null;

        [Tooltip("Optional text element that will be set to the name of the action")]
        [SerializeField] private Text _text = null;

        protected virtual void OnEnable()
        {
            if (_actionReference == null || _actionReference.action == null)
                return;

            _actionReference.action.started += OnActionStarted;
            _actionReference.action.performed += OnActionPerformed;
            _actionReference.action.canceled += OnActionCanceled;

            StartCoroutine(UpdateBinding());
        }

        protected virtual void OnDisable()
        {
            if (_actionReference == null || _actionReference.action == null)
                return;

            _actionReference.action.started -= OnActionStarted;
            _actionReference.action.performed -= OnActionPerformed;
            _actionReference.action.canceled -= OnActionCanceled;
        }

        private IEnumerator UpdateBinding()
        {
            if (null != _text)
                _text.text = _actionReference.action.name;

            while (isActiveAndEnabled)
            {
                if (_actionReference.action != null &&
                    _actionReference.action.controls.Count > 0 &&
                    _actionReference.action.controls[0].device != null &&
                    OpenXRInput.TryGetInputSourceName(_actionReference.action, 0, out var actionName, OpenXRInput.InputSourceNameFlags.Component, _actionReference.action.controls[0].device))
                {
                    if (null != _text && !string.IsNullOrEmpty(actionName))
                        _text.text = actionName;
                    OnActionBound();
                    break;
                }

                yield return new WaitForSeconds(1.0f);
            }
        }

        protected virtual void OnActionStarted(InputAction.CallbackContext ctx) { }

        protected virtual void OnActionPerformed(InputAction.CallbackContext ctx) { }

        protected virtual void OnActionCanceled(InputAction.CallbackContext ctx) { }

        protected virtual void OnActionBound()
        {
        }
    }
}