2018年2月22日 星期四

Unity內使用Tab切換輸入框的方式

話說我之前有個案子要求可以使用Tab來切換到其他輸入框,如果是Windows程式或是網頁,根本不用為此花功夫;但是Unity就沒這種天經地義的功能了,只好來動手寫一個試看看。

先確立觀念是當按下Tab時,便讓Unity去Focus到某一個介面上,如果先前已點在某一個介面上,便要像是順理成章般地到下一個介面去。

因此做了個簡單的介面:

然後在程式一開始時便Focus在帳號輸入框上,接著按Tab便可在兩個輸入框內不斷切換:
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.EventSystems;
  5.  
  6. public class XXX : MonoBehaviour {
  7.  
  8.     private GameObject account;
  9.     private GameObject password;
  10.  
  11.     void Start ()
  12.     {
  13.         account = GameObject.Find("Account");
  14.         password = GameObject.Find("Password");
  15.  
  16.         EventSystem.current.SetSelectedGameObject(account);
  17.     }
  18.  
  19.     void Update ()
  20.     {
  21.         if (Input.GetKeyDown(KeyCode.Tab))
  22.         {
  23.             if (EventSystem.current.currentSelectedGameObject == account)
  24.             {
  25.                 EventSystem.current.SetSelectedGameObject(password);
  26.             }
  27.             else if (EventSystem.current.currentSelectedGameObject == password)
  28.             {
  29.                 EventSystem.current.SetSelectedGameObject(account);
  30.             }
  31.         }
  32.     }
  33. }
  34.  

所以其實很單純,使用兩個API來取得當前Focus的GUI、和設定想Focus的GUI就好了。

EventSystem.current.currentSelectedGameObject可取得當前Focus的GUI。
EventSystem.current.SetSelectedGameObject()可設定想Focus的GUI。

用這方式可以再配合一個List來做出在複雜輸入介面上輕鬆切換的效果,我想可能有更好的觀念和寫法吧,但我自己是喜歡這個很直觀又方便修改的架構。

沒有留言:

張貼留言