DropMe.cs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using System.Reflection;
  2. using UnityEngine;
  3. using UnityEngine.EventSystems;
  4. using UnityEngine.UI;
  5. public class DropMe : MonoBehaviour, IDropHandler, IPointerEnterHandler, IPointerExitHandler
  6. {
  7. public Image containerImage;
  8. public Image receivingImage;
  9. private Color normalColor;
  10. public Color highlightColor = Color.yellow;
  11. public void OnEnable ()
  12. {
  13. if (containerImage != null)
  14. normalColor = containerImage.color;
  15. }
  16. public void OnDrop(PointerEventData data)
  17. {
  18. containerImage.color = normalColor;
  19. if (receivingImage == null)
  20. return;
  21. Sprite dropSprite = GetDropSprite (data);
  22. if (dropSprite != null)
  23. receivingImage.overrideSprite = dropSprite;
  24. }
  25. public void OnPointerEnter(PointerEventData data)
  26. {
  27. if (containerImage == null)
  28. return;
  29. Sprite dropSprite = GetDropSprite (data);
  30. if (dropSprite != null)
  31. containerImage.color = highlightColor;
  32. }
  33. public void OnPointerExit(PointerEventData data)
  34. {
  35. if (containerImage == null)
  36. return;
  37. containerImage.color = normalColor;
  38. }
  39. private Sprite GetDropSprite(PointerEventData data)
  40. {
  41. var originalObj = data.pointerDrag;
  42. if (originalObj == null)
  43. return null;
  44. var dragMe = originalObj.GetComponent<DragMe>();
  45. if (dragMe == null)
  46. return null;
  47. var srcImage = originalObj.GetComponent<Image>();
  48. if (srcImage == null)
  49. return null;
  50. return srcImage.sprite;
  51. }
  52. }