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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM