2018年2月22日 星期四

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

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

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

因此做了個簡單的介面:

然後在程式一開始時便Focus在帳號輸入框上,接著按Tab便可在兩個輸入框內不斷切換:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class XXX : MonoBehaviour {

    private GameObject account;
    private GameObject password;

    void Start ()
    {
        account = GameObject.Find("Account");
        password = GameObject.Find("Password");

        EventSystem.current.SetSelectedGameObject(account);
    }

    void Update ()
    {
        if (Input.GetKeyDown(KeyCode.Tab))
        {
            if (EventSystem.current.currentSelectedGameObject == account)
            {
                EventSystem.current.SetSelectedGameObject(password);
            }
            else if (EventSystem.current.currentSelectedGameObject == password)
            {
                EventSystem.current.SetSelectedGameObject(account);
            }
        }
    }
}


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

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

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

沒有留言:

張貼留言