按钮控件作为最常用的控件之一。为了满足项目的要求,我做了3种按钮控件,分别是普通按钮控件CGUIButton,文本按钮控件CGUITextButton和复杂按钮控件CGUIComplexButton,单选按钮CGUICheckBox以及单选按钮组。
普通按钮控件是最简单的按钮控件,它实现了鼠标移入、移出、点击、松开按钮的图片变换。由于同学已经将各种鼠标点击、移入、移出等封装成了C#的事件,所以实现代码如下:
using Assets.Scripts.Gui;
using UnityEngine;
/**
* 按钮 Button
* 直接将弹起时 点击时等图片拖上来就可以了 要监听按下事件的话可以这么写:
* using Assets.Scripts.Gui;
*
* CGUIButton b;
* b.TouchEnd += B_TouchEnd;
*
* void B_TouchEnd(object sender, TouchEndEventArgs e)
* {
* //doSomeThing
* }
*/
namespace Assets.TGUI.UIScript
{
public class CGUIButton : CInteractiveObject
{
//按钮Sprite
private SpriteRenderer m_spriteRenderer;
//按钮状态
public Sprite m_normalSp; //弹起时Sprite
public Sprite m_overSp; //悬停时Sprite
public Sprite m_clickSp; //点击时Sprite
public Sprite m_disableSp; //禁用时Sprite
protected override void Start()
{
base.Start();
//初始化按钮显示
m_spriteRenderer = this.GetComponent<SpriteRenderer>();
SetShowSprite(m_normalSp);
//预设置按钮监听
this.TouchBegin += CGUIButton_TouchBegin;
this.TouchEnd += CGUIButton_TouchEnd;
this.TouchCancelled += CGUIButton_TouchCancelled;
this.MouseEnter += CGUIButton_MouseEnter;
this.MouseLeave += CGUIButton_MouseLeave;
}
void CGUIButton_TouchCancelled(ScriptObject sender, TouchCancelledEventArgs e)
{
e.IsHandled = true;
SetShowSprite(m_normalSp);
}
void CGUIButton_MouseLeave(ScriptObject sender, MouseLeaveEventArgs e)
{
SetShowSprite(m_normalSp);
}
void CGUIButton_MouseEnter(ScriptObject sender, MouseEnterEventArgs e)
{
SetShowSprite(m_overSp);
}
/** 鼠标弹起 **/
void CGUIButton_TouchEnd(object sender, TouchEndEventArgs e)
{
e.IsHandled = true;
SetShowSprite(m_normalSp);
}
/** 鼠标点击 **/
void CGUIButton_TouchBegin(object sender, TouchBeginEventArgs e)
{
e.IsHandled = true;
SetShowSprite(m_clickSp);
}
void SetShowSprite(Sprite showSprite)
{
if (showSprite)
{
m_spriteRenderer.sprite = showSprite;
}
}
protected override void OnDestroy()
{
this.TouchBegin -= CGUIButton_TouchBegin;
this.TouchEnd -= CGUIButton_TouchEnd;
this.TouchCancelled -= CGUIButton_TouchCancelled;
this.MouseEnter -= CGUIButton_MouseEnter;
this.MouseLeave -= CGUIButton_MouseLeave;
}
}
}
继承的类:CInteractiveObject标明这个按钮是一个可交互的控件,目前这个类还是一个空类,这个类继承于同学写的GuiElement,GuiElement主要提供了各类事件。
下面是继承的简易图