NGUI的UI界面聚焦---学自于公司大神

来源:互联网 发布:tw域名要翻墙吗 编辑:程序博客网 时间:2024/04/29 09:06

不知道该不该叫聚焦,通俗点说就是:一个UI,上面好几个按钮什么的,若鼠标不点击UI或者不点击UI的子物体(按钮),UI隐藏。

直接上代码,程序员还是喜欢用代码说话

两个脚本。

1.using UnityEngine;
using System.Collections;


public class UIFocus : MonoBehaviour {
public bool SelectedChild = false;
void Start () {
        for (int index = 0,count = transform.GetChildCount();index<count;index++ )
        {
            Transform child = transform.GetChild(index);
            BoxCollider co = child.GetComponent<BoxCollider>();
            if (co != null)
            {
                UIFocusChild.SetParentFocus(child.gameObject,this);
            }
        }
}


    void OnEnable()
    {
        UICamera.selectedObject = this.gameObject;
    }

void OnSelect(bool isSelected)
{
        if (!isSelected)
        {
            if (!SelectedChild)
                gameObject.SetActive(false);
            else
                SelectedChild = false;
        }
}
}

2.

using UnityEngine;
using System.Collections;


public class UIFocusChild : MonoBehaviour {
    UIFocus ParentFocus;
void Start () {

}
    void OnPress(bool state)
    {
        if (state)
            ParentFocus.SelectedChild = true;
    }
    static public void SetParentFocus(GameObject go,UIFocus focus)
    {
        UIFocusChild focuschild = go.GetComponent<UIFocusChild>();
        if (focuschild == null)
        {
            focuschild = go.AddComponent<UIFocusChild>();
        }
        focuschild.ParentFocus = focus;
    }
}

补充,若点击了按钮, UICamera.selectedObject 就是按钮了,此时得把这个UI隐藏掉,否则,再点UI的外面是没有用的。你也可以,当点玩按钮之后,再把 UICamera.selectedObject设回去,自己琢磨必要性吧。完毕

0 0