UGUI中 關於事件的觸發,它給咱們提供了大概十七個接口可用來使用,各個接口的做用以及實現方法能夠查閱Unity官方API:html
file:///D:/Unity5.0.1/Unity/Editor/Data/Documentation/en/ScriptReference/index.html。想看具體的例子能夠借鑑Unity提供的UGUI官方實例:http://pan.baidu.com/s/1mgmpgHM
spa
裏面也有作好的拖拽實例。這邊我貼出簡單的拖拽代碼,可以讓你更容易看懂實例:code
完成拖拽須要兩個腳本 一個是drag對象 , 一個是drop對象:orm
using UnityEngine; using System.Collections; using UnityEngine.UI; using UnityEngine.EventSystems; public class dragme : MonoBehaviour,IDragHandler,IBeginDragHandler,IEndDragHandler { //生成的icon private GameObject draged_icon; public void OnBeginDrag(PointerEventData eventData) { //設置icon屬性,添加組件 draged_icon = new GameObject("icon"); draged_icon.transform.SetParent(GameObject.Find("Canvas").transform, false); draged_icon.AddComponent<RectTransform>(); draged_icon.AddComponent<Image>(); draged_icon.GetComponent<Image>().sprite = GetComponent<Image>().sprite; //讓圖標不執行事件檢測,防止icon妨礙後面的event system CanvasGroup group = draged_icon.AddComponent<CanvasGroup>(); group.blocksRaycasts = false; } public void OnDrag(PointerEventData eventData) { //在RectTransform下 實現鼠標 物體的跟隨效果 Vector3 worldpos; if (RectTransformUtility.ScreenPointToWorldPointInRectangle(draged_icon.GetComponent<RectTransform>(), eventData.position, Camera.main, out worldpos)) { draged_icon.transform.position = worldpos; } } public void OnEndDrag(PointerEventData eventData) { //銷燬圖標 if (draged_icon != null) { Destroy(draged_icon.gameObject); } } }
using UnityEngine; using System.Collections; using UnityEngine.UI; using UnityEngine.EventSystems; public class Dropme : MonoBehaviour,IPointerEnterHandler,IPointerExitHandler,IDropHandler { //鼠標進入 public void OnPointerEnter(PointerEventData eventData) { //有拖拽物,drop區域變色,不然return GameObject dragobj = eventData.pointerDrag; if (dragobj == null) return; GetComponent<Image>().color = Color.grey; } //鼠標離開 重置顏色white public void OnPointerExit(PointerEventData eventData) { GetComponent<Image>().color = Color.white; } //drop 賦予拖拽物體sprite public void OnDrop(PointerEventData eventData) { GameObject dragobj = eventData.pointerDrag; // if (dragobj == null) return; GetComponent<Image>().sprite = dragobj.GetComponent<Image>().sprite; GetComponent<Image>().color = Color.white; } }