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 2018-06-08 20:18  考拉宝贝  阅读(3836)  评论(1编辑  收藏  举报

导航