Ниже приведены несколько способов обнаружения нажатия клавиши Enter в Unity с использованием C#:
Метод 1: использование Input.GetKeyDown(KeyCode.Return)
void Update()
{
if (Input.GetKeyDown(KeyCode.Return))
{
// Enter key is pressed
// Add your code here
}
}
Метод 2: использование EventSystem.current.currentSelectedGameObject и Input.GetKeyDown(KeyCode.Return)
using UnityEngine.EventSystems;
void Update()
{
if (EventSystem.current.currentSelectedGameObject != null && Input.GetKeyDown(KeyCode.Return))
{
// Enter key is pressed and a UI element is selected
// Add your code here
}
}
Метод 3: использование EventSystem.current.IsPointerOverGameObject и Input.GetKeyDown(KeyCode.Return)
using UnityEngine.EventSystems;
void Update()
{
if (EventSystem.current.IsPointerOverGameObject() && Input.GetKeyDown(KeyCode.Return))
{
// Enter key is pressed and a UI element is selected
// Add your code here
}
}
Метод 4. Использование специального класса диспетчера ввода
public class InputManager : MonoBehaviour
{
public static event Action OnEnterKeyPressed;
void Update()
{
if (Input.GetKeyDown(KeyCode.Return))
{
OnEnterKeyPressed?.Invoke();
}
}
}
После этого вы можете подписаться на событие OnEnterKeyPressedв других скриптах, чтобы обнаружить нажатие клавиши Enter.