通過拖拽的方式監聽UGUI的事件
通過代碼添加對UGUI控件的事件監聽
using System;
using UnityEngine;
using UnityEngine.UI;
public class UIEventManager : MonoBehaviour {
public GameObject btnGameObject;
public GameObject sliderGameObject;
public GameObject dropDownGameObject;
public GameObject toggleGameObject;
// Use this for initialization
void Start () {
btnGameObject.GetComponent<Button>().onClick.AddListener(this.ButtonOnClick);//添加按鈕的監聽事件
sliderGameObject.GetComponent<Slider>().onValueChanged.AddListener(this.OnSliderChanged);//添加滑動條的監聽事件
dropDownGameObject.GetComponent<Dropdown>().onValueChanged.AddListener(this.OnDropDownChanged);//添加下拉條的監聽事件
toggleGameObject.GetComponent<Toggle>().onValueChanged.AddListener(this.OnToggleChanged);//添加單選框的監聽事件
}
//按鈕事件
void ButtonOnClick()
{
Debug.Log("ButtonOnClick");
}
//滑動條事件
void OnSliderChanged(float value)
{
Debug.Log("SliderChanged:" + value);
}
//下拉條事件
void OnDropDownChanged(Int32 value)
{
Debug.Log("DropDownChanged:" + value);
}
//單選框事件
void OnToggleChanged(bool value)
{
Debug.Log("ToggleChanged:" + value);
}
// Update is called once per frame
void Update () {
}
}
跟鼠標相關的事件接口的實現
查看相關接口
必須勾上此選項。
IPointerDownHandler |
鼠標按下 |
IPointerClickHandler |
鼠標點擊 |
IPointerUpHandler |
鼠標擡起 |
IPointerEnterHandler |
鼠標移上 |
IPointerExitHandler |
鼠標移出 |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System;
//interface
public class UIEventManager2 : MonoBehaviour
, IPointerDownHandler//鼠標按下
, IPointerClickHandler//鼠標點擊
, IPointerUpHandler//鼠標擡起
, IPointerEnterHandler//鼠標移上
, IPointerExitHandler//鼠標移出{
public void OnPointerClick(PointerEventData eventData)
{
Debug.Log("OnPointerClick");
}
public void OnPointerDown(PointerEventData eventData)
{
Debug.Log("OnPointerDown");
}
public void OnPointerEnter(PointerEventData eventData)
{
Debug.Log("OnPointerEnter");
}
public void OnPointerExit(PointerEventData eventData)
{
Debug.Log("OnPointerExit");
}
public void OnPointerUp(PointerEventData eventData)
{
Debug.Log("OnPointerUp");
}
}
跟拖拽相關的事件接口的實現
IBeginDragHandler |
開始拖拽 |
IDragHandler |
拖拽中 |
IEndDragHandler |
拖拽結束 |
IDropHandler |
拖拽完成後在對象上擡起鼠標時觸發 |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System;
//interface
public class UIEventManager2 : MonoBehaviour
,IBeginDragHandler//開始拖拽
,IDragHandler //拖拽中
,IEndDragHandler //拖拽結束
,IDropHandler //拖拽完成後在對象上擡起鼠標時觸發
{
public void OnBeginDrag(PointerEventData eventData)
{
Debug.Log("OnBeginDrag");
}
public void OnDrag(PointerEventData eventData)
{
Debug.Log("OnDrag");
}
public void OnDrop(PointerEventData eventData)
{
Debug.Log("OnDrop");
}
public void OnEndDrag(PointerEventData eventData)
{
Debug.Log("OnEndDrag");
}
}