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

Unity中如何检测玩家是否使用键鼠(无控制器连接)?

检测游戏输入设备(手柄/键鼠)

你可以通过Unity新输入系统的Keyboard.current和Mouse.current来判断键鼠场景,修改后的完整代码如下:

void Start()
{
    var gamepad = Gamepad.current;
    if (gamepad != null)
    {
        if (gamepad is DualShockGamepad)
        {
            print("Playstation gamepad");
        }
        else if (gamepad is XInputController)
        {
            print("Xbox gamepad");
        }
        else
        {
            print("Unknown gamepad");
        }
    }
    else
    {
        // 检测键鼠设备
        bool hasKeyboard = Keyboard.current != null;
        bool hasMouse = Mouse.current != null;
        
        if (hasKeyboard && hasMouse)
        {
            print("Keyboard and Mouse");
        }
        else if (hasKeyboard)
        {
            print("Only Keyboard");
        }
        else if (hasMouse)
        {
            print("Only Mouse");
        }
        else
        {
            print("No input devices detected");
        }
    }
}

关键说明:

  • 原代码中gamepad == null时直接return,现在改为进入键鼠检测分支
  • 使用Keyboard.current和Mouse.current判断对应设备是否被系统识别
  • 可根据需求拆分单独键盘/鼠标的情况,也可以合并判断为"键鼠设备"

如果需要实时监听设备切换(比如玩家中途插拔手柄/键鼠),可以在Update方法中重复检测,或者订阅输入系统的设备连接事件:

void OnEnable()
{
    InputSystem.onDeviceChange += OnDeviceChange;
}

void OnDisable()
{
    InputSystem.onDeviceChange -= OnDeviceChange;
}

void OnDeviceChange(InputDevice device, InputDeviceChange change)
{
    switch (change)
    {
        case InputDeviceChange.Added:
        case InputDeviceChange.Removed:
            DetectInputDevice();
            break;
    }
}

void DetectInputDevice()
{
    var gamepad = Gamepad.current;
    if (gamepad != null)
    {
        if (gamepad is DualShockGamepad)
        {
            print("Playstation gamepad connected");
        }
        else if (gamepad is XInputController)
        {
            print("Xbox gamepad connected");
        }
        else
        {
            print("Unknown gamepad connected");
        }
    }
    else
    {
        if (Keyboard.current != null && Mouse.current != null)
        {
            print("Switched to Keyboard and Mouse");
        }
        else
        {
            print("No input devices available");
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 17:10:10