Files
Echo/Assets/_Project/Scripts/UI/PanelStack/PlayerInputActionRouter.cs
2026-07-08 20:42:51 +08:00

97 lines
3.2 KiB
C#

using UnityEngine;
#if ENABLE_INPUT_SYSTEM
using UnityEngine.InputSystem;
#endif
namespace UI.PanelStack
{
public class PlayerInputActionRouter : MonoBehaviour
{
[SerializeField] private bool debugLogs = true;
[SerializeField] private string pauseActionName = "Pause";
[SerializeField] private string cancelActionName = "Cancel";
#if ENABLE_INPUT_SYSTEM
private PlayerInput playerInput;
private void OnEnable()
{
TryBind();
}
private void OnDisable()
{
Unbind();
}
private void TryBind()
{
playerInput = FindPrimaryPlayerInput();
if (playerInput == null)
{
if (debugLogs) Debug.Log("[PlayerInputActionRouter] No PlayerInput found; input routing disabled.");
return;
}
playerInput.onActionTriggered += OnActionTriggered;
if (debugLogs)
{
string map = playerInput.currentActionMap != null ? playerInput.currentActionMap.name : "(null)";
bool hasPause = playerInput.actions != null && playerInput.actions.FindAction(pauseActionName, false) != null;
bool hasCancel = playerInput.actions != null && playerInput.actions.FindAction(cancelActionName, false) != null;
Debug.Log($"[PlayerInputActionRouter] Bound. currentMap={map}, hasPause={hasPause}, hasCancel={hasCancel}");
}
}
private static PlayerInput FindPrimaryPlayerInput()
{
Player.PlayerController playerController = FindObjectOfType<Player.PlayerController>(true);
if (playerController != null)
{
PlayerInput playerInput = playerController.GetComponentInChildren<PlayerInput>(true);
if (playerInput != null) { return playerInput; }
}
return FindObjectOfType<PlayerInput>(true);
}
private void Unbind()
{
if (playerInput != null)
{
playerInput.onActionTriggered -= OnActionTriggered;
}
playerInput = null;
}
private void OnActionTriggered(InputAction.CallbackContext ctx)
{
if (ctx.action == null) { return; }
if (ctx.performed == false) { return; }
if (UIPanelStack.Instance == null) { return; }
string actionName = ctx.action.name;
if (actionName == cancelActionName)
{
bool closed = UIPanelStack.Instance.CloseTop();
if (debugLogs) Debug.Log($"[PlayerInputActionRouter] {cancelActionName} performed. closedTop={closed}");
return;
}
if (actionName == pauseActionName)
{
if (UIPanelStack.Instance.IsAnyOpen())
{
if (debugLogs) Debug.Log($"[PlayerInputActionRouter] {pauseActionName} performed but stack not empty.");
return;
}
bool opened = UIPanelStack.Instance.TryOpenOnEscapeWhenEmpty();
if (debugLogs) Debug.Log($"[PlayerInputActionRouter] {pauseActionName} performed. openedMenu={opened}");
}
}
#endif
}
}