功能介绍:
如图,全键盘控制,UIkeynavigation选择rounds,coins,music这些button,回车键选择相应的编辑框,按上下键修改label的数值,再按回车键退出选择的编辑框
先看看UIkeynavigation的源码:
protected virtual void OnClick ()
{
if (NGUITools.GetActive (this) && NGUITools.GetActive (onClick))
{
UICamera.selectedObject = onClick;
EditActiveValue.isActive = islabel();
editActiveValue.activeObject = onClick;
}
}
onClick就是我们要获取的object
接下来新建脚本EditActiveValue.cs,并修改源码,将onClick通过引用传递到新建的脚本当中
EditActiveValue.cs代码如下:
using UnityEngine;
using System.Collections;
public class EditActiveValue : MonoBehaviour
{
//要编辑的object
public GameObject activeObject = null;
//object上的UIlabel组件
private UILabel label;
//只有当选中编辑框的时候,才能在update()中修改label中的text
public static bool isActive = false;
// Update is called once per frame
void Update ()
{
if(isActive)
Edit( ref activeObject );
}
public void Edit(ref GameObject activeObject)
{
if(activeObject == null ) return;
if(activeObject.tag.CompareTo("label") == 0)
{
label = activeObject.GetComponent<UILabel>();
if (Input.GetKeyDown (KeyCode.DownArrow))
{
int temp;
int.TryParse(label.text, out temp);
temp--;
label.text = temp.ToString();
}
if (Input.GetKeyDown (KeyCode.UpArrow))
{
int temp;
int.TryParse(label.text, out temp);
temp++;
label.text = temp.ToString();
}
}
}
}
为了不修改源码,新建一个脚本NewUIkeynavigation.cs,继承UIkeynavigation类,代码如下:
using UnityEngine;
using System.Collections;
public class NewUIKeyNavigation : UIKeyNavigation
{
public EditActiveValue editActiveValue;
void Start()
{
editActiveValue = GameObject.Find ("EditActiveValue").GetComponent<EditActiveValue> ();
}
protected override void OnClick ()
{
if (NGUITools.GetActive (this) && NGUITools.GetActive (onClick))
{
UICamera.selectedObject = onClick;
EditActiveValue.isActive = islabel();
editActiveValue.activeObject = onClick;
}
}
bool islabel()
{
if(onClick.GetComponent<UILabel>() != null)
{
return true;
}
else
{
return false;
}
}
}