使用UGUI制作NGUI的UI Key Navigation

来源:互联网 发布:ajax json 解析 编辑:程序博客网 时间:2024/05/24 01:42

新项目要使用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 initializationvoid Start(){    this.eventSystem = EventSystem.current;}// Update is called once per framevoid 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的功能。
好了,这篇就写到这里!

0 0
原创粉丝点击