今天做一个拖动图像的demo,效果图如下:
1 拖动的类需要实现 IDropHandler, IPointerEnterHandler, IPointerExitHandler 这三个接口;
2 接受的类需要实现 IBeginDragHandler,IDragHandler,IEndDragHandler 这三个接口:
下面贴代码
Drag.cs
using UnityEngine;using UnityEngine.EventSystems;using UnityEngine.UI;//拖动要集成三个接口:IBeginDragHandler,IDragHandler,IEndDragHandler[RequireComponent(typeof(Image))]public class Drag : MonoBehaviour,IBeginDragHandler,IDragHandler,IEndDragHandler { //是否与面板保持平行 public bool dragOnSurfaces = true; private GameObject m_DragIcon; private RectTransform m_RectPlane; public void OnBeginDrag(PointerEventData eventData) { var canvas = FindInParent
Drop.cs
using UnityEngine;using UnityEngine.EventSystems;using UnityEngine.UI;//接收拖动的类需要实现的三个接口:IDropHandler, IPointerEnterHandler, IPointerExitHandlerpublic class Drop : MonoBehaviour, IDropHandler, IPointerEnterHandler, IPointerExitHandler{ public Image containerImage; public Image receivingImage; private Color normalColor; public Color highLightColor = Color.blue; public void OnEnable() { if (containerImage != null) normalColor = containerImage.color; } //释放对象 public void OnDrop(PointerEventData eventData) { containerImage.color = normalColor; //没有图像直接返回 if (receivingImage == null) return; Sprite dropSprite = GetDropSprite(eventData); if (dropSprite != null) receivingImage.sprite = dropSprite; } //对象移到接受面板,面板高亮 public void OnPointerEnter(PointerEventData eventData) { if (containerImage == null) return; Sprite dropSprite = GetDropSprite(eventData); if (dropSprite != null) containerImage.color = highLightColor; } public void OnPointerExit(PointerEventData eventData) { if (containerImage == null) return; containerImage.color = normalColor; } //获取图像数据 private Sprite GetDropSprite(PointerEventData data) { var originalObj = data.pointerDrag; if (originalObj == null) return null; var srcImage = originalObj.GetComponent(); if (srcImage == null) return null; return srcImage.sprite; }}
demo源文件