Unity3D旧项目OnGUI中Gui.Button键盘选中切换方案问询
Unity OnGUI 按钮键盘导航解决方案
核心实现思路
- 维护当前选中按钮的索引值,通过键盘按键切换索引
- 给选中的按钮添加视觉高亮效果模拟鼠标悬停
- 绑定A键触发当前选中按钮的点击逻辑,S/上箭头、A/下箭头切换选中项
完整代码示例
using UnityEngine; public class OldUIMenu : MonoBehaviour { // 按钮文本列表,对应"开始游戏""选项""退出游戏" private string[] buttonTexts = { "开始游戏", "选项", "退出游戏" }; // 当前选中的按钮索引 private int selectedIndex = 0; // 按键冷却时间,防止连续按键快速切换 private float inputCooldown = 0.2f; private float lastInputTime; void Update() { // 冷却时间内不处理输入 if (Time.time - lastInputTime < inputCooldown) return; // 下箭头/A键:切换到下一个按钮,循环回到开头 if (Input.GetKeyDown(KeyCode.DownArrow) || Input.GetKeyDown(KeyCode.A)) { selectedIndex++; if (selectedIndex >= buttonTexts.Length) selectedIndex = 0; lastInputTime = Time.time; } // 上箭头/S键:切换到上一个按钮,循环回到末尾 if (Input.GetKeyDown(KeyCode.UpArrow) || Input.GetKeyDown(KeyCode.S)) { selectedIndex--; if (selectedIndex < 0) selectedIndex = buttonTexts.Length - 1; lastInputTime = Time.time; } // A键触发当前选中按钮的点击事件(和鼠标点击逻辑一致) if (Input.GetKeyUp(KeyCode.A)) { OnButtonClicked(selectedIndex); } } void OnGUI() { // 按钮基础样式 GUIStyle normalStyle = GUI.skin.button; // 选中按钮的高亮样式 GUIStyle selectedStyle = new GUIStyle(normalStyle); selectedStyle.normal.background = MakeTex(2, 2, new Color(0.3f, 0.6f, 1f)); // 遍历绘制所有按钮 for (int i = 0; i < buttonTexts.Length; i++) { Rect buttonRect = new Rect(25, 25 + i * 40, 100, 30); // 根据是否选中选择样式 GUIStyle currentStyle = (i == selectedIndex) ? selectedStyle : normalStyle; // 鼠标点击或选中时按A键触发 if (GUI.Button(buttonRect, buttonTexts[i], currentStyle)) { OnButtonClicked(i); } } } // 按钮点击逻辑处理 private void OnButtonClicked(int index) { switch (index) { case 0: Debug.Log("开始游戏"); // 这里添加开始游戏的逻辑 break; case 1: Debug.Log("打开选项"); // 这里添加选项菜单的逻辑 break; case 2: Debug.Log("退出游戏"); Application.Quit(); break; } } // 生成简单的高亮背景纹理 private Texture2D MakeTex(int width, int height, Color col) { Color[] pix = new Color[width * height]; for (int i = 0; i < pix.Length; i++) pix[i] = col; Texture2D result = new Texture2D(width, height); result.SetPixels(pix); result.Apply(); return result; } }
关键细节说明
- 输入冷却:避免按住按键时快速连续切换索引,提升操作体验
- 高亮样式:通过复制默认按钮样式并修改背景色,模拟鼠标悬停效果,无需额外资源
- 循环切换:当切换到边界时自动回到列表另一端,保证菜单的循环导航
- 事件统一处理:鼠标点击和键盘触发共用同一个
OnButtonClicked方法,逻辑一致
内容的提问来源于stack exchange,提问作者Wonder76
相关产品推荐
相关产品推荐

