纳金网

标题: UGUI事件触发代码 [打印本页]

作者: may    时间: 2015-11-22 08:42
标题: UGUI事件触发代码


//14.事件实例解析---------------------------------------------------------------------------------------------
UGUI中 事件触发分为:被动触发,主动触发


示例: Button组件怎么触发按钮事件?

public class Button : Selectable, IPointerClickHandler, ISubmitHandler
{...}
按钮组件继承了Selectable类;实现了点击事件,提交事件.


源码:
  1. //按钮类 Button.cs
  2.        
  3. // Event delegates triggered on click.
  4. [FormerlySerializedAs("onClick")]
  5. [SerializeField]
  6. private ButtonClickedEvent m_OnClick = new ButtonClickedEvent();

  7. // Trigger all registered callbacks.
  8. public virtual void OnPointerClick(PointerEventData eventData)
  9. {
  10.         if (eventData.button != PointerEventData.InputButton.Left)
  11.                 return;

  12.         Press();//如果点击了鼠标左键,说明按钮被按了
  13. }

  14. private void Press()
  15. {
  16.         if (!IsActive() || !IsInteractable())
  17.                 return;

  18.         m_OnClick.Invoke(); //如果按钮显示着,并且允许进行交互,就执行按钮点击事件处理函数
  19. }


  20. public virtual void OnSubmit(BaseEventData eventData)
  21. {
  22.         Press();

  23.         // if we get set disabled during the press
  24.         // don't run the coroutine. 如果我们的按钮是禁用的,则不响应这个协程
  25.         if (!IsActive() || !IsInteractable())
  26.                 return;

  27.         DoStateTransition(SelectionState.Pressed, false);//设置按钮不再处于按下状态
  28.         StartCoroutine(OnFinishSubmit());  //执行按钮被点击后的事情
  29. }

  30. private IEnumerator OnFinishSubmit()
  31. {
  32.         var fadeTime = colors.fadeDuration;
  33.         var elapsedTime = 0f;

  34.         while (elapsedTime < fadeTime)
  35.         {
  36.                 elapsedTime += Time.unscaledDeltaTime;
  37.                 yield return null;
  38.         }

  39.         DoStateTransition(currentSelectionState, false);
  40. }
复制代码
其他组件事件实现也类似.

UGUI官方相关示例: Drag and drop
拖 DragMe.cs
放 DropMe.cs

public class DragMe : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{...}

public class DropMe : MonoBehaviour, IDropHandler, IPointerEnterHandler, IPointerExitHandler
{...}







欢迎光临 纳金网 (http://rs.narkii.com/club/) Powered by Discuz! X2.5