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

如何实现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

方法二:自定义脚本控制(灵活度更高)

如果需要个性化输入逻辑,可编写简单脚本实现循环导航:

  1. 创建名为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);
    }
}
  1. 将脚本挂载到暂停菜单的父物体上
  2. 在Inspector面板中,把Resume、Options、Quit三个按钮按顺序拖入menuButtons数组
  3. 确保Input Manager中的Vertical轴为默认配置(已支持键盘方向键和控制器D-pad)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 00:30:03