unity 自定义功能快捷键

自用贴,自定义功能对应的快捷键,组合键只添加了项目中需要的。

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 指定功能配置快捷键
/// </summary>
public class InputKeyCode
{
    // key=功能id,list<int>=键位id
    public static Dictionary<int, List<int>> inputKeyDic = new Dictionary<int, List<int>>();
    /// <summary>
    /// 功能默认对应的快捷键
    /// </summary>
    public static void DefaultInputKeyDic()
    {
        inputKeyDic.Clear();
        List<int> tempList = new List<int>();
        tempList.Add((int)KeyCode.Q);
        inputKeyDic.Add(0,tempList);

        tempList = new List<int>();
        tempList.Add((int)KeyCode.T);
        inputKeyDic.Add(1, tempList);

        tempList = new List<int>();
        tempList.Add((int)KeyCode.E);
        inputKeyDic.Add(2, tempList);

        tempList = new List<int>();
        tempList.Add((int)KeyCode.R);
        inputKeyDic.Add(3, tempList);

        tempList = new List<int>();
        tempList.Add((int)KeyCode.W);
        inputKeyDic.Add(4, tempList);

        tempList = new List<int>();
        tempList.Add((int)KeyCode.Z);
        inputKeyDic.Add(5, tempList);

        tempList = new List<int>();
        tempList.Add((int)KeyCode.F1);
        inputKeyDic.Add(6, tempList);

        tempList = new List<int>();
        tempList.Add((int)KeyCode.F);
        inputKeyDic.Add(7, tempList);

        tempList = new List<int>();
        tempList.Add((int)KeyCode.LeftControl);
        tempList.Add((int)KeyCode.Z);
        inputKeyDic.Add(8, tempList);

        tempList = new List<int>();
        tempList.Add((int)KeyCode.LeftControl);
        tempList.Add((int)KeyCode.Y);
        inputKeyDic.Add(9, tempList);

        tempList = new List<int>();
        tempList.Add((int)KeyCode.LeftControl);
        tempList.Add((int)KeyCode.A);
        inputKeyDic.Add(10, tempList);

        tempList = new List<int>();
        tempList.Add((int)KeyCode.C);
        inputKeyDic.Add(11, tempList);

        tempList = new List<int>();
        tempList.Add((int)KeyCode.LeftControl);
        tempList.Add((int)KeyCode.S);
        inputKeyDic.Add(12, tempList);

        tempList = new List<int>();
        tempList.Add((int)KeyCode.LeftControl);
        tempList.Add((int)KeyCode.V);
        inputKeyDic.Add(13, tempList);

        tempList = new List<int>();
        tempList.Add((int)KeyCode.D);
        inputKeyDic.Add(14, tempList);

        tempList = new List<int>();
        tempList.Add((int)KeyCode.LeftControl);
        tempList.Add((int)KeyCode.C);
        inputKeyDic.Add(15, tempList);

    }
    /// <summary>
    /// 保存功能对应的快捷键配置,偷懒使用了PlayerPrefs,可以重写成本地文件自己维护
    /// </summary>
    public static void SaveInputKeyDic()
    {
        FunctionType functionType = new FunctionType();
        int count = Enum.GetValues(functionType.GetType()).Length;
        Debug.Log("SaveInputKeyDic count=" + count);
        for (int i = 0; i < count; i++)
        {
            string value = string.Empty;
            for (int j = 0; j < inputKeyDic[i].Count; j++)
            {
                if (j == 1)
                    value += "&" + inputKeyDic[i][j];
                else
                    value += inputKeyDic[i][j];
            }
            SetString("key" + i, value);
        }
    }
    public static void LoadInputKeyDic()
    {
        FunctionType functionType = new FunctionType();
        int count = Enum.GetValues(functionType.GetType()).Length;
        Debug.Log("LoadInputKeyDic count=" + count);
        for (int i = 0; i < count; i++)
        {
            string[] value = GetString("key" + i).Split('&');
            List<int> list = new List<int>();
            for (int j = 0; j < value.Length; j++)
            {
                if (!string.IsNullOrEmpty(value[j]))
                    list.Add(int.Parse(value[j]));
            }
            if (i == 6)
            {
                if (list.Count == 1 && list[0] == (int)KeyCode.LeftAlt)
                {
                    list[0] = (int)KeyCode.F1;
                }
            }

            if (list.Count > 0)
                inputKeyDic[i] = list;
        }
    }

    /// <summary>
    /// 在update中调用,传入对应的功能id,返回对应的快捷键是否被按下
    /// </summary>
    /// <param name="functionType"></param>
    /// <returns></returns>
    public static bool GetKeyDownEvent(FunctionType functionType)
    {
        List<int> tempList = inputKeyDic[(int)functionType];
        if (tempList.Count > 0)
        {
            if (tempList.Count > 1)
            {
                if ((KeyCode)tempList[0] == KeyCode.LeftAlt || (KeyCode)tempList[0] == KeyCode.RightAlt)
                {
                    return GetAlt_Letter((KeyCode)tempList[1]);
                }
                else if ((KeyCode)tempList[0] == KeyCode.LeftControl || (KeyCode)tempList[0] == KeyCode.RightControl)
                {
                    return GetControl_Letter((KeyCode)tempList[1]);
                }
                else if ((KeyCode)tempList[0] == KeyCode.LeftShift || (KeyCode)tempList[0] == KeyCode.RightShift)
                {
                    return GetShift_Letter((KeyCode)tempList[1]);
                }
                else if ((KeyCode)tempList[0] == KeyCode.Space)
                {
                    return GetSpace_Letter((KeyCode)tempList[1]);
                }
            }
            else
            {
                KeyCode key = (KeyCode)tempList[0];
                if (key == KeyCode.LeftAlt || key == KeyCode.RightAlt)
                {
                    return GetAltDown();
                }
                if (key == KeyCode.LeftShift || key == KeyCode.RightShift)
                {
                    return GetShiftDown();
                }
                if (key == KeyCode.LeftControl || key == KeyCode.RightControl)
                {
                    return GetControlDown();
                }

                return !GetAltKey() && !GetShiftKey() && !GetControlKey() && Input.GetKeyDown(key);
            }
        }
        return false;
    }
    //====================================================组合键==============================================
    /// <summary>
    /// 左右ctrl+key
    /// </summary>
    /// <param name="keyCode"></param>
    /// <returns></returns>
    public static bool GetControl_Letter(KeyCode keyCode)
    {
        if (GetControlKey() && Input.GetKeyDown(keyCode))
        {
            return true;
        }
        return false;
    }
    /// <summary>
    /// 左右ctrl
    /// </summary>
    /// <returns></returns>
    public static bool GetControlKey()
    {
        if (Input.GetKey(KeyCode.LeftControl)||Input.GetKey(KeyCode.RightControl))
        {
            return true;
        }
        return false;
    }
    /// <summary>
    /// 左右alt+key
    /// </summary>
    /// <param name="keyCode"></param>
    /// <returns></returns>
    public static bool GetAlt_Letter(KeyCode keyCode)
    {
        if (GetAltKey() && Input.GetKeyDown(keyCode))
        {
            return true;
        }
        return false;
    }
    /// <summary>
    /// 左右alt
    /// </summary>
    /// <returns></returns>
    public static bool GetAltKey()
    {
        if (Input.GetKey(KeyCode.LeftAlt) || Input.GetKey(KeyCode.RightAlt))
        {
            return true;
        }
        return false;
    }
    /// <summary>
    /// 左右shift+key
    /// </summary>
    /// <param name="keyCode"></param>
    /// <returns></returns>
    public static bool GetShift_Letter(KeyCode keyCode)
    {
        if (GetShiftKey() && Input.GetKeyDown(keyCode))
        {
            return true;
        }
        return false;
    }
    /// <summary>
    /// 空格+key
    /// </summary>
    /// <param name="keyCode"></param>
    /// <returns></returns>
    public static bool GetSpace_Letter(KeyCode keyCode)
    {
        if (GetSpaceKey() && Input.GetKeyDown(keyCode))
        {
            return true;
        }
        return false;
    }
    /// <summary>
    /// 左右shift
    /// </summary>
    /// <returns></returns>
    public static bool GetShiftKey()
    {
        if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))
        {
            return true;
        }
        return false;
    }

    public static bool GetSpaceKey()
    {
        if (Input.GetKey(KeyCode.Space))
        {
            return true;
        }
        return false;
    }
    /// <summary>
    /// 回车键,包括小键盘的
    /// </summary>
    /// <returns></returns>
    public static bool GetEnterKeyDown()
    {
        if (Input.GetKeyDown(KeyCode.KeypadEnter)|| Input.GetKeyDown(KeyCode.Return))
        {
            return true;
        }
        return false;
    }
    /// <summary>
    /// tab按下
    /// </summary>
    /// <returns></returns>
    public static bool GetTabKeyDown()
    {
        if (Input.GetKeyDown(KeyCode.Tab))
        {
            return true;
        }
        return false;
    }
    //====================================================组合键 END==============================================

    public static bool GetAltDown()
    {
        if (Input.GetKeyDown(KeyCode.LeftAlt)|| Input.GetKeyDown(KeyCode.RightAlt))
        {
            return true;
        }
        return false;
    }
    public static bool GetShiftDown()
    {
        if (Input.GetKeyDown(KeyCode.LeftShift) || Input.GetKeyDown(KeyCode.RightShift))
        {
            return true;
        }
        return false;
    }
    public static bool GetControlDown()
    {
        if (Input.GetKeyDown(KeyCode.LeftControl) || Input.GetKeyDown(KeyCode.RightControl))
        {
            return true;
        }
        return false;
    }
    public static bool MouseRightDown()
    {
        return Input.GetMouseButtonDown(1);
    }
    public static bool MouseRightPress()
    {
        return Input.GetMouseButton(1);
    }
    public static bool MouseLeftDown()
    {
        return Input.GetMouseButtonDown(0);
    }
    public static bool MouseLeftPress()
    {
        return Input.GetMouseButton(0);
    }
    public static bool MouseMiddleDown()
    {
        return Input.GetMouseButtonDown(2);
    }
    public static bool MouseMiddlePress()
    {
        return Input.GetMouseButton(2);
    }

    public static bool GetUpArrowDown()
    {
        return Input.GetKeyDown(KeyCode.UpArrow);
    }
    public static bool GetUpArrow()
    {
        return Input.GetKey(KeyCode.UpArrow);
    }
    public static bool GetDownArrowDown()
    {
        return Input.GetKeyDown(KeyCode.DownArrow);
    }
    public static bool GetDownArrow()
    {
        return Input.GetKey(KeyCode.DownArrow);
    }
    public static bool GetLeftArrowDown()
    {
        return Input.GetKeyDown(KeyCode.LeftArrow);
    }
    public static bool GetLeftArrow()
    {
        return Input.GetKey(KeyCode.LeftArrow);
    }
    public static bool GetRightArrowDown()
    {
        return Input.GetKeyDown(KeyCode.RightArrow);
    }
    public static bool GetRightArrow()
    {
        return Input.GetKey(KeyCode.RightArrow);
    }

    //============================封装PlayerPrefs=============================================
    public static bool HasKey(string keyName)
    {
        return PlayerPrefs.HasKey(keyName);
    }

    public static int GetInt(string keyName)
    {
        return PlayerPrefs.GetInt(keyName);
    }

    public static void SetInt(string keyName, int valueInt)
    {
        PlayerPrefs.SetInt(keyName, valueInt);
    }

    public static float GetFloat(string keyName)
    {
        return PlayerPrefs.GetFloat(keyName);
    }

    public static void SetFloat(string keyName, float valueFloat)
    {
        PlayerPrefs.SetFloat(keyName, valueFloat);
    }

    public static string GetString(string keyName, string defaultValue)
    {
        return PlayerPrefs.GetString(keyName, defaultValue);
    }
    public static string GetString(string keyName)
    {
        return PlayerPrefs.GetString(keyName);
    }
    public static void SetString(string keyName, string valueString)
    {
        PlayerPrefs.SetString(keyName, valueString);
    }

    public static void DeleteAllKey()
    {
        PlayerPrefs.DeleteAll();
    }

    public static void DeleteTheKey(string keyName)
    {
        PlayerPrefs.DeleteKey(keyName);
    }

    //============================封装PlayerPrefs END=============================================
}
/// <summary>
/// 快捷对应的功能类型
/// </summary>
public enum FunctionType
{
    DrawPoint = 0,
    DrawCircle = 1,
    DrawCurve = 2,
    DrawCurve2 = 3,
    DrawLine = 4,
    DrawLine2 = 5,
    ShowDistance = 6,
    CheckDistance = 7,
    Revocation = 8,
    Advance = 9,
    SelectedAll = 10,
    CancelDraw = 11,
    Save = 12,
    Paste = 13,
    Delete = 14,
    Copy = 15,

}
<think>首先,用户的问题是:“我想查找在Unity中使用快捷键触发方法的实现方式 请问在Unity中如何使用快捷键触发方法”。所以,我需要专注于如何在Unity中使用快捷键来触发方法。 回顾系统级指令: - 所有行内数学表达式使用$...$格式。 - 独立公式使用$$...$$格式并单独成段。 - LaTeX语法正确。 - 使用中文回答。 - 生成相关问题。 - 回答中引用的段落末尾自然地添加引用标识,如[^1]。 用户提供了几个引用: - 引用[1]:关于Unity快捷键的一般列表。 - 引用[2]:关于MenuItem特性,用于在菜单中添加自定义命令。 - 引用[3]:关于Visual Studio调试快捷键。 - 引用[4]:关于Unity 3D菜单栏和快捷键详解。 用户说:“上述引用仅供参考,并不是用户真正的需求,请尽可能多的参考用户上一次的问题和你的回答。” 但在这个对话中,这是第一条消息,所以没有“上一次的问题”。我应该基于当前问题和提供的引用来回答。 关键点是:用户想知道在Unity中如何使用快捷键触发方法。从提供的引用中,特别是引用[2]提到了MenuItem特性,这在Unity编辑器中用于创建菜单项,并可以指定快捷键。 在Unity中,使用快捷键触发自定义方法通常是通过MenuItem特性实现,它可以附加到编辑器脚本中的静态方法上,并允许指定快捷键。 我的回答应该: 1. 解释如何使用MenuItem特性。 2. 提供代码示例。 3. 确保结构清晰。 4. 使用中文。 5. 在末尾生成相关问题。 6. 如果有引用,添加引用标识。 步骤: - 介绍MenuItem特性。 - 解释如何在路径中指定快捷键。 - 给出一个代码示例。 - 讨论其他可能的方式(如Input.GetKeyDown在运行时)。 - 生成相关问题。 代码示例需要用代码块格式。 最后,添加相关问题。 回答结构: 1. 简要介绍如何实现。 2. 详细步骤。 3. 代码示例。 4. 注意事项。 5. 相关问题。 确保LaTeX正确:虽然这个问题没有数学内容,但如果有数学表达式,要用正确的格式。 现在,基于引用: - 引用[2]说:MenuItem特性用于在Unity编辑器菜单中添加自定义命令,参数控制菜单项的位置、顺序、快捷键等。 - 引用[4]提到了一些快捷键。 所以,我应该强调MenuItem特性。 完整回答: - 第一步:使用Unity的MenuItem特性。 - 例如,MenuItem("Tools/My Command _g"),其中_g指定快捷键为G。 - 提供示例代码。 - 解释快捷键语法:如%表示Ctrl,&表示Alt等。 - 提到运行时快捷键(使用Input类)。 - 添加引用:引用[2]。 相关问题: 1. 如何自定义Unity编辑器的快捷键? 2. MenuItem特性支持哪些修饰键? 3. 在Unity运行时如何检测按键事件? </think>### 在Unity中使用快捷键触发方法的实现方式 在Unity中,使用快捷键触发自定义方法主要通过两种方式实现:(1) **编辑器模式下**使用`[MenuItem]`特性创建菜单项并绑定快捷键;(2) **运行时模式下**监听按键事件(例如在MonoBehaviour脚本中使用`Input.GetKeyDown`)。以下我将逐步解释并给出代码示例,确保实现清晰可靠。 #### 1. **编辑器模式:使用 MenuItem 特性** Unity的`[MenuItem]`特性允许在编辑器的菜单栏中添加自定义命令,并支持快捷键绑定。快捷键语法使用特殊字符指定修饰键: - `%` 表示 Ctrl (Windows) 或 Command (macOS) - `&` 表示 Alt - `#` 表示 Shift - `_` 后跟单个字符表示快捷键字母(例如 `_g` 表示 G 键) **实现步骤:** 1. 创建一个编辑器脚本(必须放在`Assets/Editor`文件夹下)。 2. 定义一个静态方法,并用`[MenuItem("菜单路径")]`修饰。 3. 在菜单路径中包含快捷键语法。 **代码示例:** ```csharp using UnityEditor; using UnityEngine; public class CustomShortcutExample { // 绑定快捷键 Ctrl+Shift+G(Windows)或 Command+Shift+G(macOS),触发后执行方法 [MenuItem("Tools/Execute Method %#g")] public static void TriggerMethod() { Debug.Log("快捷键触发了自定义方法!"); // 在这里添加你的自定义逻辑,例如调用其他方法 } } ``` - **解释**: - `"Tools/Execute Method %#g"`:菜单项路径为"Tools > Execute Method",快捷键为 Ctrl+Shift+G。 - 当用户在Unity编辑器中按下快捷键时,`TriggerMethod()`方法会被自动调用。 - 快捷键设置需符合Unity规范,例如避免与系统快捷键冲突[^2]。 #### 2. **运行时模式:使用 Input 类监听按键** 在游戏运行时(Play Mode),快捷键触发方法需要在MonoBehaviour脚本中使用`Input.GetKeyDown`或`Input.GetKey`检测按键事件。 **实现步骤:** 1. 创建一个游戏对象附加脚本。 2. 在`Update()`方法中检测按键输入。 3. 调用自定义方法。 **代码示例:** ```csharp using UnityEngine; public class RuntimeShortcutExample : MonoBehaviour { void Update() { // 检测快捷键 Alt+T 按下时触发方法 if (Input.GetKeyDown(KeyCode.T) && (Input.GetKey(KeyCode.LeftAlt) || Input.GetKey(KeyCode.RightAlt))) { ExecuteRuntimeMethod(); } } private void ExecuteRuntimeMethod() { Debug.Log("运行时快捷键触发了方法!"); // 在这里添加游戏逻辑 } } ``` - **解释**: - `Input.GetKeyDown(KeyCode.T)`检测T键按压事件。 - 结合`Input.GetKey(KeyCode.LeftAlt)`确保Alt修饰键被按住。 - 这种方式适用于游戏交互,但仅在Play Mode中生效[^3]。 #### 注意事项 - **编辑器 vs 运行时**:`[MenuItem]`只工作在编辑器模式,而Input类适用于运行时。选择合适的方式基于场景。 - **快捷键冲突**:避免与Unity内置快捷键(如F键聚焦对象[^4])或系统快捷键冲突。 - **跨平台兼容**:修饰键符号(如`%`)自动适配Windows/macOS。 - **性能考虑**:在运行时频繁检测按键可能影响性能,建议在`Update()`中优化判断逻辑。 如需更多快捷键参考,可查阅Unity文档或编辑器设置(Edit > Shortcuts Manager)[^1][^4]。 ### 相关问题 1. 如何自定义Unity编辑器的全局快捷键(非菜单项)? 2. 在Unity中如何检测组合键(如Ctrl+Alt+Click)的事件? 3. MenuItem特性支持哪些快捷键修饰符?可否绑定功能键(F1-F12)?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值