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

如何获取Unity中KeyCode枚举里以Alpha开头的枚举值?

只检测Unity中数字键(KeyCode.AlphaN系列)的实现方案

你可以通过三种方式筛选出KeyCode中名称以Alpha开头的枚举值,只检测数字键:

方法一:使用Linq快速筛选(简洁高效)

需要先引入System.Linq命名空间,通过Linq的筛选方法直接获取目标枚举值集合:

using System.Linq;
using UnityEngine;

public class KeyDetector : MonoBehaviour
{
    void Update()
    {
        // 筛选所有名称以"Alpha"开头的KeyCode
        var numericKeys = System.Enum.GetValues(typeof(KeyCode))
            .Cast<KeyCode>()
            .Where(key => key.ToString().StartsWith("Alpha"));

        foreach (KeyCode key in numericKeys)
        {
            if (Input.GetKey(key))
            {
                Debug.Log("数字键按下: " + key);
            }
        }
    }
}

方法二:在原有循环中添加判断(无需额外命名空间)

直接在你原来的循环里增加名称判断,跳过非Alpha开头的枚举值:

using UnityEngine;

public class KeyDetector : MonoBehaviour
{
    void Update()
    {
        foreach (KeyCode key in System.Enum.GetValues(typeof(KeyCode)))
        {
            // 仅处理名称以"Alpha"开头的按键
            if (key.ToString().StartsWith("Alpha") && Input.GetKey(key))
            {
                Debug.Log("数字键按下: " + key);
            }
        }
    }
}

方法三:直接枚举Alpha0到Alpha9(性能最优)

因为数字键对应的KeyCode固定是Alpha0到Alpha9,可以直接循环生成这些枚举值,避免遍历所有KeyCode:

using UnityEngine;

public class KeyDetector : MonoBehaviour
{
    void Update()
    {
        // 循环生成Alpha0到Alpha9对应的KeyCode
        for (int num = 0; num <= 9; num++)
        {
            KeyCode numericKey = (KeyCode)System.Enum.Parse(typeof(KeyCode), "Alpha" + num);
            if (Input.GetKey(numericKey))
            {
                Debug.Log("数字键按下: " + numericKey);
            }
        }
    }
}

这三种方法都能实现你的需求,其中方法三的性能最好,因为不需要遍历全部KeyCode枚举值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 13:02:18