unity InputField按下tab自动切换

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<Selectable>();

                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<InputField>();
                    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上面
运行尝试即可

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值