Unity 5.4可用的UGUI中按Tab切换InputField脚本

本文代码原始地址:http://icemark.cn/blog/?p=253

代码经过修改,可用在Unity 5.4使用。感谢原作者!

使用方法:确认将InputField里的Navigation设置为Automatic,然后将本脚本挂在上面。即可使用Tab和Shift+Tab在挂载脚本的InputField之间切换。

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class InputNavigator : MonoBehaviour, ISelectHandler, IDeselectHandler
{
    EventSystem _system;
    private bool _isSelect = false;

    void Start()
    {
        _system = EventSystem.current;
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Tab) && _isSelect)
        {

            Selectable next = null;
            if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))
            {
                next = _system.currentSelectedGameObject.GetComponent().FindSelectableOnUp();
            }
            else
            {
                next = _system.currentSelectedGameObject.GetComponent().FindSelectableOnDown();
            }
            if (next != null)
            {
                InputField inputfield = next.GetComponent();
                _system.SetSelectedGameObject(next.gameObject, new BaseEventData(_system));
            }
            else
            {
                Debug.LogError("找不到下一个控件");
            }
        }
    }

    public void OnSelect(BaseEventData eventData)
    {
        _isSelect = true;
    }

    public void OnDeselect(BaseEventData eventData)
    {
        _isSelect = false;
    }
}


你可能感兴趣的:(unity,UI开发)