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 }
复制代码
  • 5
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值