Как сделать поочередное нажатие клавиш?

Я хочу, чтобы, к примеру, при нажатие клавиши Esc и затем клавиши a происходило действие (например, открытие канваса) или так, чтобы сначала любую из этих клавиш нажать, а потом вторую.


Ответы (1 шт):

Автор решения: KOTlK

Самый примитивный пример. Контракт:

namespace KeyCombinations
{
    public interface IKeyInput
    {
        bool Performed { get; }
    }
}

Комбинация:

using UnityEngine;

namespace KeyCombinations
{
    public class KeyCombination : IKeyInput
    {
        private readonly KeyCode _first;
        private readonly KeyCode _second;

        public KeyCombination(KeyCode first, KeyCode second)
        {
            _first = first;
            _second = second;
        }

        public bool Performed => (Input.GetKey(_first) && Input.GetKeyDown(_second));
    }
}

Использование:

using UnityEngine;

namespace KeyCombinations
{
    public class Test : MonoBehaviour
    {
        private readonly IKeyInput _keyInput = new KeyCombination(KeyCode.LeftShift, KeyCode.F);

        private void Update()
        {
            if (_keyInput.Performed)
            {
                Debug.Log("Combination performed");
            }
        }
    }
}

Если нужно, чтобы отображалось в инспекторе:

using System;
using UnityEngine;

namespace KeyCombinations
{
    [Serializable]
    public class KeyCombination : IKeyInput
    {
        [SerializeField] private KeyCode _first;
        [SerializeField] private KeyCode _second;

        public KeyCombination(KeyCode first, KeyCode second)
        {
            _first = first;
            _second = second;
        }

        public bool Performed => (Input.GetKey(_first) && Input.GetKeyDown(_second));
    }
}
using UnityEngine;

namespace KeyCombinations
{
    public class Test : MonoBehaviour
    {
        [SerializeField] private KeyCombination _keyInput;

        private void Update()
        {
            if (_keyInput.Performed)
            {
                Debug.Log("Combination performed");
            }
        }
    }
}
→ Ссылка