DropArea.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. using System.Collections;
  2. using System;
  3. using UnityEngine;
  4. using UnityEngine.UIElements;
  5. namespace UnityEditor.Rendering.LookDev
  6. {
  7. class DropArea
  8. {
  9. readonly Type[] k_AcceptedTypes;
  10. bool droppable;
  11. public DropArea(Type[] acceptedTypes, VisualElement area, Action<UnityEngine.Object, Vector2> OnDrop)
  12. {
  13. k_AcceptedTypes = acceptedTypes;
  14. area.RegisterCallback<DragPerformEvent>(evt => Drop(evt, OnDrop));
  15. area.RegisterCallback<DragEnterEvent>(evt => DragEnter(evt));
  16. area.RegisterCallback<DragLeaveEvent>(evt => DragLeave(evt));
  17. area.RegisterCallback<DragExitedEvent>(evt => DragExit(evt));
  18. area.RegisterCallback<DragUpdatedEvent>(evt => DragUpdate(evt));
  19. }
  20. void DragEnter(DragEnterEvent evt)
  21. {
  22. droppable = false;
  23. foreach (UnityEngine.Object obj in DragAndDrop.objectReferences)
  24. {
  25. if (!IsInAcceptedTypes(obj.GetType()))
  26. continue;
  27. droppable = true;
  28. evt.StopPropagation();
  29. return;
  30. }
  31. }
  32. void DragLeave(DragLeaveEvent evt)
  33. {
  34. foreach (UnityEngine.Object obj in DragAndDrop.objectReferences)
  35. {
  36. if (!IsInAcceptedTypes(obj.GetType()))
  37. continue;
  38. DragAndDrop.visualMode = DragAndDropVisualMode.Rejected;
  39. evt.StopPropagation();
  40. return;
  41. }
  42. }
  43. void DragExit(DragExitedEvent evt)
  44. {
  45. foreach (UnityEngine.Object obj in DragAndDrop.objectReferences)
  46. {
  47. if (!IsInAcceptedTypes(obj.GetType()))
  48. continue;
  49. DragAndDrop.visualMode = DragAndDropVisualMode.Rejected;
  50. evt.StopPropagation();
  51. return;
  52. }
  53. }
  54. void DragUpdate(DragUpdatedEvent evt)
  55. {
  56. foreach (UnityEngine.Object obj in DragAndDrop.objectReferences)
  57. {
  58. if (!IsInAcceptedTypes(obj.GetType()))
  59. continue;
  60. DragAndDrop.visualMode = droppable ? DragAndDropVisualMode.Link : DragAndDropVisualMode.Rejected;
  61. evt.StopPropagation();
  62. }
  63. }
  64. void Drop(DragPerformEvent evt, Action<UnityEngine.Object, Vector2> OnDrop)
  65. {
  66. bool atLeastOneAccepted = false;
  67. foreach (UnityEngine.Object obj in DragAndDrop.objectReferences)
  68. {
  69. if (!IsInAcceptedTypes(obj.GetType()))
  70. continue;
  71. OnDrop.Invoke(obj, evt.localMousePosition);
  72. atLeastOneAccepted = true;
  73. }
  74. if (atLeastOneAccepted)
  75. {
  76. DragAndDrop.AcceptDrag();
  77. evt.StopPropagation();
  78. }
  79. }
  80. bool IsInAcceptedTypes(Type testedType)
  81. {
  82. foreach (Type type in k_AcceptedTypes)
  83. {
  84. if (testedType.IsAssignableFrom(type))
  85. return true;
  86. }
  87. return false;
  88. }
  89. }
  90. }