Из за чего Multi Hold в New Input System не работает?
В скрипте ниже я подрубаю Input, потом передаю его в InputManagerи уже использую в нужных мне классах.
У меня он создан как для кнопок клавиатуры, но дополнительно использую OnScreenButton для такого же ввода на телефоны ( с него возможности потестить нет).
И если я зажимаю W - в классе GameTester выводится Vertical, а если D - то Horizontal, но если и W и D То вызывается что то одно, почему так и как это пофиксить?
Вместо switch case делал через if ещё, не помогло. Так же создавал отдельно методы для вызова горизонтали и вертикали, тоже не особо работает
public void Initialize(CarInput carInput, Button gasButton, Button brakeButton, Button rightButton, Button leftButton) { gasButton.gameObject.AddComponent<OnScreenButton>().controlPath = "<Keyboard>/w"; brakeButton.gameObject.AddComponent<OnScreenButton>().controlPath = "<Keyboard>/s"; rightButton.gameObject.AddComponent<OnScreenButton>().controlPath = "<Keyboard>/d"; leftButton.gameObject.AddComponent<OnScreenButton>().controlPath = "<Keyboard>/a"; carInput.UI.Move.started += ctx => OnMovePressed(ctx.ReadValue<Vector2>().normalized); carInput.UI.Move.canceled += ctx => OnMoveCanceled(); } private void OnMovePressed(Vector2 dir) { Direction newDirection = GetDirection(dir); switch (newDirection) { case Direction.Up: GasPressed?.Invoke(dir); goto case Direction.Down; case Direction.Down: BrakePressed?.Invoke(dir); goto case Direction.Left; case Direction.Left: TurnLeftPressed?.Invoke(dir); goto case Direction.Right; case Direction.Right: TurnRightPressed?.Invoke(dir); break; } } |
public void Initialize(CarInput carInput, Button gasButton, Button brakeButton, Button rightButton, Button leftButton) { gasButton.gameObject.AddComponent<OnScreenButton>().controlPath = "<Keyboard>/w"; brakeButton.gameObject.AddComponent<OnScreenButton>().controlPath = "<Keyboard>/s"; rightButton.gameObject.AddComponent<OnScreenButton>().controlPath = "<Keyboard>/d"; leftButton.gameObject.AddComponent<OnScreenButton>().controlPath = "<Keyboard>/a"; carInput.UI.Move.started += ctx => OnMovePressed(ctx.ReadValue<Vector2>().normalized); carInput.UI.Move.canceled += ctx => OnMoveCanceled(); } private void OnMovePressed(Vector2 dir) { Direction newDirection = GetDirection(dir); switch (newDirection) { case Direction.Up: GasPressed?.Invoke(dir); goto case Direction.Down; case Direction.Down: BrakePressed?.Invoke(dir); goto case Direction.Left; case Direction.Left: TurnLeftPressed?.Invoke(dir); goto case Direction.Right; case Direction.Right: TurnRightPressed?.Invoke(dir); break; } }
public class InputManager { public Vector2 Verical { get; private set; } public Vector2 Horizontal { get; private set; } public void Initialize(UIController uiController) { uiController.GasPressed += SetVertical; uiController.BrakePressed += SetVertical; uiController.TurnRightPressed += SetHorizontal; uiController.TurnLeftPressed += SetHorizontal; } private void SetVertical(Vector2 value) { Verical = value; } private void SetHorizontal(Vector2 value) { Horizontal = value; } } |
public class InputManager { public Vector2 Verical { get; private set; } public Vector2 Horizontal { get; private set; } public void Initialize(UIController uiController) { uiController.GasPressed += SetVertical; uiController.BrakePressed += SetVertical; uiController.TurnRightPressed += SetHorizontal; uiController.TurnLeftPressed += SetHorizontal; } private void SetVertical(Vector2 value) { Verical = value; } private void SetHorizontal(Vector2 value) { Horizontal = value; } }
public class GameTester : MonoBehaviour { [Inject] private InputManager _inputManager; private void Update() { Debug.Log($"Vertical: {_inputManager.Verical}"); Debug.Log($"Horizontal: {_inputManager.Horizontal}"); } } |
public class GameTester : MonoBehaviour { [Inject] private InputManager _inputManager; private void Update() { Debug.Log($"Vertical: {_inputManager.Verical}"); Debug.Log($"Horizontal: {_inputManager.Horizontal}"); } }
Дополнительно:
Ответы:
вообщем из за
carInput.UI.Move.started += ctx => OnMovePressed(ctx.ReadValue<Vector2>().normalized); |
carInput.UI.Move.started += ctx => OnMovePressed(ctx.ReadValue<Vector2>().normalized);
я получал только одну ось, ту - которая была первая нажата
public void Update() { GetInvokeInput(); } private void GetInvokeInput() { _inputDir = _carInput.UI.Move.ReadValue<Vector2>(); InputPressed?.Invoke(_inputDir); } |
public void Update() { GetInvokeInput(); } private void GetInvokeInput() { _inputDir = _carInput.UI.Move.ReadValue<Vector2>(); InputPressed?.Invoke(_inputDir); }
вот так работает
Опишите проблему, и специалист поможет с настройкой, исправлением ошибки или доработкой сайта. Подберём понятный план работ без лишней переписки.
Пока нет других ответов. Будьте первым, кто поможет автору.
Ответить на вопрос

Проблема с Multi Hold в New Input System может возникать по нескольким причинам. Вот несколько возможных причин и способы их решения:
1. Неправильная настройка Input System: Убедитесь, что вы правильно настроили Input System для работы с Multi Hold. Убедитесь, что вы правильно настроили кнопки для удержания нескольких входов одновременно.
using UnityEngine; using UnityEngine.InputSystem; public class MultiHoldExample : MonoBehaviour { private InputAction holdAction; private void OnEnable() { holdAction = new InputAction(binding: "/space", interactions: "Hold(duration=0.5)"); holdAction.Enable(); holdAction.started += ctx => Debug.Log("Hold started"); holdAction.canceled += ctx => Debug.Log("Hold canceled"); } private void OnDisable() { holdAction.Disable(); } }
2. Проблемы с обработкой событий: Проверьте, что вы правильно обрабатываете события начала и отмены удержания кнопки. Убедитесь, что вы используете правильные методы для обработки этих событий.
3. Конфликты с другими скриптами: Проверьте, нет ли конфликтов с другими скриптами, которые могут перехватывать входные данные. Убедитесь, что ваш скрипт имеет приоритет в обработке входных данных.
Если после выполнения этих шагов проблема с Multi Hold в New Input System все еще не решена, попробуйте создать минимальный рабочий пример и задать вопрос на форуме сообщества Unity для получения дополнительной помощи.