Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
【Unity】UI ToolkitのDragAndDropサンプル
using UnityEngine;
using UnityEngine.UIElements;
/// <summary>
/// DragAndDrop Sample
/// </summary>
[RequireComponent(typeof(UIDocument))]
public class UIToolkit_DragAndDropTest : MonoBehaviour
{
private Vector2 _dragOffset;
void OnEnable()
{
var document = GetComponent<UIDocument>();
var rootVisualElement = document.rootVisualElement;
var dragTarget = rootVisualElement.Q<VisualElement>("dragTarget");
dragTarget.RegisterCallback<PointerDownEvent>(OnPointerDown);
dragTarget.RegisterCallback<PointerMoveEvent>(OnPointerMove);
dragTarget.RegisterCallback<PointerUpEvent>(OnPointerUp);
}
private void OnPointerDown(PointerDownEvent evt)
{
evt.target.CapturePointer(evt.pointerId);
var draggedTarget = (VisualElement) evt.target;
_dragOffset = new Vector2(draggedTarget.resolvedStyle.left, draggedTarget.resolvedStyle.top)
- new Vector2(evt.position.x, evt.position.y);
}
private void OnPointerMove(PointerMoveEvent evt)
{
if (evt.target.HasPointerCapture(evt.pointerId))
{
var pos = new Vector2(evt.position.x, evt.position.y) + _dragOffset;
var draggedTarget = (VisualElement) evt.target;
draggedTarget.style.left = pos.x;
draggedTarget.style.top = pos.y;
}
}
private void OnPointerUp(PointerUpEvent evt)
{
if (evt.target.HasPointerCapture(evt.pointerId))
{
evt.target.ReleasePointer(evt.pointerId);
}
}
}
<ui:UXML xmlns:ui="UnityEngine.UIElements" editor-extension-mode="False">
<ui:VisualElement name="container" style="height: 100%; width: 100%; background-color: rgb(255, 255, 186);">
<ui:VisualElement name="dragTarget" style="width: 119px; height: 106px; background-color: rgba(255, 175, 28, 255);" />
</ui:VisualElement>
</ui:UXML>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment