You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity新Input Manager下,Android应用如何通过代码触发输入动作?

问题:Unity新输入系统中如何通过代码触发Input Action

我正在开发基于Unity引擎的Android应用,需要通过代码触发各类输入动作(如键盘左箭头键)。目前已采用新Input Manager,并创建了PlayerControls.cs,但不清楚如何在代码中正确触发Input Action,现有代码示例如下:

private PlayerControls _playerControls;
private void Start()
{
 _playerControls = new PlayerControls();
 _playerControls.Player.Enable();
}
private void MoveLeft()
{
 //Don't know what to do here
 _playerControls.Player.LeftKey.performed += ctx => Debug.Log("Move Left");
}

自动生成的PlayerControls.cs包含LeftKey按钮类型的Action,绑定到键盘左箭头键。当前在MoveLeft方法中仅添加了performed事件监听,不知如何实现触发LeftKey输入动作的逻辑。


解决方案

针对Unity新输入系统的代码触发需求,提供三种常用实现方式:

方法1:直接触发单次Action(最简方案)

对于按钮类的Input Action,直接调用Perform()方法即可模拟一次完整的输入触发,会自动触发performed回调:

private void MoveLeft()
{
    // 直接触发LeftKey的performed事件
    _playerControls.Player.LeftKey.Perform();
}

注意事项:

  • 确保_playerControls.Player已经通过Enable()启用,否则Action不会响应。
  • 此方法适合模拟单次按键(比如点击触发一次左移)。

方法2:模拟完整的输入生命周期(按住/松开场景)

如果需要模拟“按住按键→持续触发→松开按键”的完整流程,可以通过TriggerAction方法手动触发不同阶段的回调:

private void MoveLeftHold()
{
    // 模拟按键按下(触发started事件)
    _playerControls.Player.LeftKey.TriggerAction(InputActionPhase.Started);
    
    // 模拟持续按住(可多次触发performed事件)
    _playerControls.Player.LeftKey.TriggerAction(InputActionPhase.Performed);
    
    // 模拟按键松开(触发canceled事件)
    _playerControls.Player.LeftKey.TriggerAction(InputActionPhase.Canceled);
}

适用场景:

  • 需要模拟长按输入(比如持续左移直到松开)的逻辑。

方法3:通过回调接口规范处理(长期维护方案)

利用自动生成代码中的IPlayerActions接口,统一处理输入逻辑,同时可以直接调用回调方法模拟输入:

  1. 让你的MonoBehaviour实现IPlayerActions接口:
public class YourPlayerScript : MonoBehaviour, PlayerControls.IPlayerActions
{
    private PlayerControls _playerControls;

    private void Start()
    {
        _playerControls = new PlayerControls();
        // 设置回调接口
        _playerControls.Player.SetCallbacks(this);
        _playerControls.Player.Enable();
    }

    // 实现IPlayerActions的回调方法
    public void OnLeftKey(InputAction.CallbackContext context)
    {
        if (context.performed)
        {
            Debug.Log("Move Left");
            // 在这里编写实际的左移逻辑
        }
    }

    private void MoveLeft()
    {
        // 直接调用回调方法模拟输入触发
        OnLeftKey(new InputAction.CallbackContext());
        // 或者用Perform()触发完整流程
        _playerControls.Player.LeftKey.Perform();
    }
}

优势:

  • 符合新输入系统的设计规范,逻辑更清晰,便于后续维护扩展。
  • 统一处理用户输入和代码模拟输入的逻辑,避免重复代码。

内容的提问来源于stack exchange,提问作者Ted Logan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 18:43:12