使用UGUI制作NGUI的UI Key Navigation

新项目要使用UGUI,虽然平时也使用过,但是一直都没用在项目上,到底有多少的坑也不得而知。
最近在学习到Navigation的时候,一直很迷茫到底该怎样使用才能像NGUI的UI Key Navigation的效果,但是试过很多次都没有成功。经过半天的摸索才发现,原来UGUI没有帮我们写好这些脚本来实现这个功能。但是好在UGUI提供了这样的组件,我们只需要稍微的写几句代码就可以实现。
但是,还得做个对比嘛,我们在使用NGUI的Navigation时只需要在对象上面加上这里写图片描述
left,right,up,down放当前对象的方位对象,点击tab键就会自动切换,如果没有,就不拖放对象。
好了,UGUI没那么方便。直接上代码吧!

“`
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class Test : MonoBehaviour
{

private EventSystem eventSystem;

// Use this for initialization
void Start()
{

    this.eventSystem = EventSystem.current;
}

// Update is called once per frame
void Update()
{
    // When TAB is pressed, we should select the next selectable UI element
    if (Input.GetKeyDown(KeyCode.Tab))
    {
        Selectable next = null;
        Selectable current = null;

        // Figure out if we have a valid current selected gameobject
        if (eventSystem.currentSelectedGameObject != null)
        {
            // Unity doesn't seem to "deselect" an object that is made inactive
            if (eventSystem.currentSelectedGameObject.activeInHierarchy)
            {
                current = eventSystem.currentSelectedGameObject.GetComponent<Selectable>();
            }
        }

        if (current != null)
        {
            // When SHIFT is held along with tab, go backwards instead of forwards
            if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))
            {
                next = current.FindSelectableOnLeft();
                if (next == null)
                {
                    next = current.FindSelectableOnUp();
                }
            }
            else
            {
                next = current.FindSelectableOnRight();
                if (next == null)
                {
                    next = current.FindSelectableOnDown();
                    if (next ==null)
                    {
                        current = eventSystem.firstSelectedGameObject.GetComponent<Selectable>();
                        next = current;
                    }
                }
            }
        }
        else
        {
            // If there is no current selected gameobject, select the first one
            if (Selectable.allSelectables.Count > 0)
            {
                next = Selectable.allSelectables[0];
            }
        }

        if (next != null)
        {
            next.Select();
        }
    }
}

}
测试看看:
这里写图片描述
只需要点击tab就可以切换,当然点击shift+tab就可以向上切换。确实是实现了NGUI的功能。
好了,这篇就写到这里!

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值