Unity Input System 按键代码动态绑定学习笔记

Unity Input System 按键代码动态绑定学习笔记

C#代码如下:

using TMPro;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.UI;

public class KeyBindingCtrl : MonoBehaviour
{
    public TMP_Text keyText;
    private InputAction upAction;
    private InputAction downAction;
    private void Start()
    {
        UpActionBinding();
        DownActionBinding();
    }
    void UpActionBinding()
    {
        // 创建输入动作
        upAction = new InputAction("UpAction");

        // 添加带两个修饰键的绑定
        upAction.AddCompositeBinding("ButtonWithTwoModifiers")
            .With("Modifier1", "<Keyboard>/ctrl")
            .With("Modifier2", "<Keyboard>/shift")
            .With("Button", "<Keyboard>/w");

        // 添加回调
        upAction.performed += ctx => OnUpArrowAction();
        upAction.Enable();
    }

    void DownActionBinding()
    {
        
        downAction = new InputAction(
            name: "DownAction",
            type: InputActionType.Button
        );

       
        downAction.AddCompositeBinding("OneModifier")
            .With("Modifier", "<Keyboard>/ctrl")
            .With("Binding", "<Keyboard>/s");

       
        downAction.performed += ctx => OnDownArrowAction();
        downAction.Enable();
    }

    void OnDownArrowAction()
    {
       /* Debug.Log("Ctrl + s pressed!");*/
        keyText.text = "Ctrl + s pressed!";
        
    }


    private void OnUpArrowAction()
    {
       /* Debug.Log("Ctrl+Shift+T pressed!");*/
        keyText.text = "Ctrl+Shift+W pressed!";
        // 执行逻辑
    }

    private void OnDestroy()
    {
        upAction?.Dispose();
        downAction?.Dispose(); // Cleanup
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AgilityBaby

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值