Unity3D的InputField输入框控件按下Tab键光标自动切换

一、进行垂直布局输入框
Unity3D的InputField输入框控件按下Tab键光标自动切换_第1张图片
二、编写一个脚本使用TAB键切换光标的脚本
/***
*	Title:"XXX" 项目
*		主题:使用Tab键切换输入框的光标
*	Description:
*		功能:XXX
*	Date:2017
*	Version:0.1版本
*	Author:Coffee
*	Modify Recoder:
*/

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

namespace Test
{
    public class ChangeCursorTest : MonoBehaviour, ISelectHandler, IDeselectHandler
    {
        private EventSystem system;                                 //事件系统
        private bool isSelect = false;                              //光标是否在当前输入框标志
        public Direction direction = Direction.vertical;            //垂直切换输入框的光标



        //枚举光标切换的方向
        public enum Direction
        {
            //垂直切换
            vertical = 0,
            //水平切换
            horizontal = 1
        }
        void Start()
        {
            system = EventSystem.current;
        }

        void Update()
        {
            if (Input.GetKeyDown(KeyCode.Tab) && isSelect)
            {
                Selectable next = null;
                var current = system.currentSelectedGameObject.GetComponent();

                int mark = Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift) ? 1 : -1;
                Vector3 dir = direction == Direction.horizontal ? Vector3.left * mark : Vector3.up * mark;
                next = GetNextSelectable(current, dir);

                if (next != null)
                {
                    var inputField = next.GetComponent();
                    if (inputField == null) return;
                    StartCoroutine(Wait(next));
                }
            }
        }

        private static Selectable GetNextSelectable(Selectable current, Vector3 dir)
        {
            Selectable next = current.FindSelectable(dir);
            if (next == null)
                next = current.FindLoopSelectable(-dir);
            return next;
        }

        IEnumerator Wait(Selectable next)
        {
            yield return new WaitForEndOfFrame();
            system.SetSelectedGameObject(next.gameObject, new BaseEventData(system));
        }

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

        public void OnDeselect(BaseEventData eventData)
        {
            isSelect = false;
        }
    }//class_end
    public static class Develop
    {
        public static Selectable FindLoopSelectable(this Selectable current, Vector3 dir)
        {
            Selectable first = current.FindSelectable(dir);
            if (first != null)
            {
                current = first.FindLoopSelectable(dir);
            }
            return current;
        }
    }


}

三、将该脚本添加给布局中的每一个InputField输入框
四、运行项目,将光标定位到输入框的位置,按下Tab键光标就会自动切换到下一个输入框

你可能感兴趣的:(Unity基础)