Unity3D - UGUI实现Tab键切换输入框、按钮(按Tab键切换高亮显示的UI)
1.在Hierarchy面板创建能被选中的UI(Button、InputField等)。
2.在Canvas上创建C#脚本 TabCutPichon。
3.编写脚本。
1 using System.Collections; 2 using System.Collections.Generic; 3 using UnityEngine; 4 using UnityEngine.EventSystems; 5 6 public class TabCutPitchOn : MonoBehaviour 7 { 8 // 得到EventSystem组件 9 private EventSystem system; 10 // 字典:key 游戏物体编号,游戏物体 11 private Dictionary<int,GameObject> dicObj; 12 // 用于存储得到的字典的索引 13 private int index; 14 15 void Start () 16 { 17 // 初始化字段 18 system = EventSystem.current; 19 dicObj = new Dictionary<int, GameObject> (); 20 index = 0; 21 // 给字典赋值 22 for (int i = 0; i < transform.childCount; i++) { 23 dicObj.Add (i, transform.GetChild (i).gameObject); 24 } 25 // 得到字典中对应索引的游戏物体 26 GameObject obj; 27 dicObj.TryGetValue (index, out obj); 28 // 设置第一个可交互的UI为高亮状态 29 system.SetSelectedGameObject (obj, new BaseEventData (system)); 30 } 31 32 void Update () 33 { 34 // 当有 UI 高亮(得到高亮的UI,不为空)并且 按下Tab键 35 if (system.currentSelectedGameObject != null && Input.GetKeyDown (KeyCode.Tab)) { 36 // 得到当前高亮状态的 UI 物体 37 GameObject hightedObj = system.currentSelectedGameObject; 38 // 看是场景中第几个物体 39 foreach (KeyValuePair<int,GameObject> item in dicObj) { 40 if (item.Value == hightedObj) { 41 index = item.Key + 1; 42 // 超出索引 将Index归零 43 if (index == dicObj.Count) { 44 index = 0; 45 } 46 break; 47 } 48 } 49 // 得到对应索引的游戏物体 50 GameObject obj; 51 dicObj.TryGetValue (index, out obj); 52 // 使得到的游戏物体高亮 53 system.SetSelectedGameObject (obj, new BaseEventData (system)); 54 } 55 } 56 }
分类:
Unity3D - UGUI
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?