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 }
复制代码

 

posted on   考拉宝贝  阅读(3923)  评论(1编辑  收藏  举报

编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示