- 最后登录
- 2019-12-25
- 注册时间
- 2012-8-24
- 阅读权限
- 90
- 积分
- 71088
- 纳金币
- 52336
- 精华
- 343
|
//14.事件实例解析---------------------------------------------------------------------------------------------
UGUI中 事件触发分为:被动触发,主动触发
示例: Button组件怎么触发按钮事件?
public class Button : Selectable, IPointerClickHandler, ISubmitHandler
{...}
按钮组件继承了Selectable类;实现了点击事件,提交事件.
源码:- //按钮类 Button.cs
-
- // Event delegates triggered on click.
- [FormerlySerializedAs("onClick")]
- [SerializeField]
- private ButtonClickedEvent m_OnClick = new ButtonClickedEvent();
- // Trigger all registered callbacks.
- public virtual void OnPointerClick(PointerEventData eventData)
- {
- if (eventData.button != PointerEventData.InputButton.Left)
- return;
- Press();//如果点击了鼠标左键,说明按钮被按了
- }
- private void Press()
- {
- if (!IsActive() || !IsInteractable())
- return;
- m_OnClick.Invoke(); //如果按钮显示着,并且允许进行交互,就执行按钮点击事件处理函数
- }
- 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()); //执行按钮被点击后的事情
- }
- private IEnumerator OnFinishSubmit()
- {
- var fadeTime = colors.fadeDuration;
- var elapsedTime = 0f;
- while (elapsedTime < fadeTime)
- {
- elapsedTime += Time.unscaledDeltaTime;
- yield return null;
- }
- DoStateTransition(currentSelectionState, false);
- }
复制代码 其他组件事件实现也类似.
UGUI官方相关示例: Drag and drop
拖 DragMe.cs
放 DropMe.cs
public class DragMe : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{...}
public class DropMe : MonoBehaviour, IDropHandler, IPointerEnterHandler, IPointerExitHandler
{...}
|
|