如何实现UI面板按下下箭头时底部按钮跳转高亮顶部按钮?
Unity暂停菜单按钮循环高亮解决方案
方法一:利用Unity内置Navigation实现(推荐)
这是最快捷的原生实现方式,无需编写代码:
- 选中菜单中的任意按钮,在Inspector面板找到Button组件下的Navigation模块
- 将Navigation模式从默认的
Automatic切换为Vertical(适配垂直排列的菜单) - 在Navigation的Advanced选项中,勾选Wrap Around选项——按下方向键到首尾项时会自动循环到另一端
- 若你的Unity版本无
Wrap Around选项,可切换为Explicit模式手动指定导航目标:- Resume按钮:
On Down设为Options,On Up设为Quit to Main Menu - Options按钮:
On Down设为Quit to Main Menu,On Up设为Resume - Quit to Main Menu按钮:
On Down设为Resume,On Up设为Options
- Resume按钮:
方法二:自定义脚本控制(灵活度更高)
如果需要个性化输入逻辑,可编写简单脚本实现循环导航:
- 创建名为
LoopMenuNavigation.cs的脚本,代码如下:
using UnityEngine; using UnityEngine.UI; using UnityEngine.EventSystems; public class LoopMenuNavigation : MonoBehaviour { public Button[] menuButtons; private int currentSelectedIndex = 0; void Start() { // 初始选中第一个按钮(与Event Manager的First Selected保持一致) EventSystem.current.SetSelectedGameObject(menuButtons[currentSelectedIndex].gameObject); } void Update() { // 检测下方向输入(键盘+控制器) if (Input.GetKeyDown(KeyCode.DownArrow) || (Input.GetAxisRaw("Vertical") < 0 && Input.GetButtonDown("Vertical"))) { currentSelectedIndex = (currentSelectedIndex + 1) % menuButtons.Length; SwitchSelectedButton(); } // 检测上方向输入(键盘+控制器) else if (Input.GetKeyDown(KeyCode.UpArrow) || (Input.GetAxisRaw("Vertical") > 0 && Input.GetButtonDown("Vertical"))) { currentSelectedIndex = (currentSelectedIndex - 1 + menuButtons.Length) % menuButtons.Length; SwitchSelectedButton(); } } private void SwitchSelectedButton() { EventSystem.current.SetSelectedGameObject(menuButtons[currentSelectedIndex].gameObject); } }
- 将脚本挂载到暂停菜单的父物体上
- 在Inspector面板中,把Resume、Options、Quit三个按钮按顺序拖入
menuButtons数组 - 确保Input Manager中的
Vertical轴为默认配置(已支持键盘方向键和控制器D-pad)
内容的提问来源于stack exchange,提问作者Michael Thompson
相关产品推荐
相关产品推荐

