0%

Unity3D UGUI 源码学习 Button

UI中用于响应点击事件的组件。阅读本文之前强烈建议先阅读Unity3D UGUI 源码学习 Selectable

1
public class Button : Selectable, IPointerClickHandler, ISubmitHandler

继承自Selectable,实现了IPointerClickHandlerISubmitHandler

Selectable

Selectable相比增加了点击的回调事件:

1
2
3
4
5
6
7
8
9
[FormerlySerializedAs("onClick")]
[SerializeField]
private ButtonClickedEvent m_OnClick = new ButtonClickedEvent();

public ButtonClickedEvent onClick
{
get { return m_OnClick; }
set { m_OnClick = value; }
}

会在响应点击Click和提交Submit时调用。

IPointerClickHandler

需要实现方法OnPointerClick(PointerEventData eventData)

1
2
3
4
5
6
7
public virtual void OnPointerClick(PointerEventData eventData)
{
if (eventData.button != PointerEventData.InputButton.Left)
return;

Press();
}

判断如果是左键PointerEventData.InputButton.Left则调用私有方法Press()

1
2
3
4
5
6
7
private void Press()
{
if (!IsActive() || !IsInteractable())
return;

m_OnClick.Invoke();
}

如果是激活状态且可交互,则调用m_OnClick。点击时的动画效果在Selectable中(OnPointerDown() 等方法)。

ISubmitHandler

实现方法OnSubmit(BaseEventData eventData)

1
2
3
4
5
6
7
8
9
10
11
12
public virtual void OnSubmit(BaseEventData eventData)
{
Press();

// if we get set disabled during the press
// don't run the coroutine.
if (!IsActive() || !IsInteractable())
return;

DoStateTransition(SelectionState.Pressed, false);
StartCoroutine(OnFinishSubmit());
}

先直接调用Press(),如果是激活状态且可交互,则先切换到SelectionState.Pressed,然后启用一个协程,等待一段时间后调用基类的DoStateTransition方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
private IEnumerator OnFinishSubmit()
{
var fadeTime = colors.fadeDuration;
var elapsedTime = 0f;

while (elapsedTime < fadeTime)
{
elapsedTime += Time.unscaledDeltaTime;
yield return null;
}

DoStateTransition(currentSelectionState, false);
}

本系列其它文章详见Unity3D UGUI 源码学习

REFERENCE