Version: 2021.3+
Drag-and-drop is a common feature in UI(User Interface) Allows a user to interact with your application. Unity currently supports three UI systems. More info
See in Glossary design. You can use UI Toolkit to create a drag-and-drop UI inside a custom Editor window or inside an application built by Unity. This example demonstrates how to create a drag-and-drop UI inside a custom Editor window.
The example adds several slots and one object in a custom Editor window. You can drag the object into any slot, as shown below:
You can find the completed files that this example creates in this GitHub repository.
This guide is for developers familiar with the Unity Editor, UI Toolkit, and C# scripting. Before you start, get familiar with the following:
To start, create a default custom Editor window from the menu. Change the menu name and window title to Drag And Drop
, and remove the code for the default labels, to make the UI more user-friendly.
Create a project in Unity with any template.
Right-click in the Assets
folder and select Create > UI Toolkit > Editor Window.
In UI Toolkit Editor Window Creator, enter DragAndDropWindow
.
Click Confirm. This automatically creates three files: DragAndDropWindow.cs
, DragAndDropWindow.uxml
, and DragAndDropWindow.uss
.
Replace the content of DragAndDropWindow.cs
with the following:
using UnityEditor; using UnityEngine; using UnityEngine.UIElements; using UnityEditor.UIElements; public class DragAndDropWindow : EditorWindow { [MenuItem("Window/UI Toolkit/Drag And Drop")] public static void ShowExample() { DragAndDropWindow wnd = GetWindow<DragAndDropWindow>(); wnd.titleContent = new GUIContent("Drag And Drop"); } public void CreateGUI() { // Each editor window contains a root VisualElement object VisualElement root = rootVisualElement; // Import UXML var visualTree = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("Assets/Editor/DragAndDropWindow.uxml"); VisualElement labelFromUXML = visualTree.Instantiate(); root.Add(labelFromUXML); // A stylesheet can be added to a VisualElement. // The style will be applied to the VisualElement and all of its children. var styleSheet = AssetDatabase.LoadAssetAtPath<StyleSheet>("Assets/Editor/DragAndDropWindow.uss"); } }
Next, add UI controls to your custom window:
slots
with two children named slot_row1
and slot_row2
. Each row should have two children named slot1
and slot2
.object
at the same level as slots
. object
must come after slots
in the Hierarchy.Style the UI controls as the following:
slot1
and slot2
, style them as 80px X 80px squares with white background color and rounded corners. Line up the slots as two rows with two slots in each row.object
, style it as a 50px X 50px round spot with a black background color.Tip: To make your project more fun, you can use a background image for the object. You can find the image (Pouch.png) in the GitHub repository.
Replace the content of DragAndDropWindow.uxml
with the following:
<ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements" xsi="http://www.w3.org/2001/XMLSchema-instance" engine="UnityEngine.UIElements" editor="UnityEditor.UIElements" noNamespaceSchemaLocation="../../../UIElementsSchema/UIElements.xsd" editor-extension-mode="False"> <Style src="DragAndDropWindow.uss" /> <ui:VisualElement name="slots"> <ui:VisualElement name="slot_row1" class="slot_row"> <ui:VisualElement name="slot1" class="slot" /> <ui:VisualElement name="slot2" class="slot" /> </ui:VisualElement> <ui:VisualElement name="slot_row2" class="slot_row"> <ui:VisualElement name="slot1" class="slot" /> <ui:VisualElement name="slot2" class="slot" /> </ui:VisualElement> </ui:VisualElement> <ui:VisualElement name="object" class="object" /> </ui:UXML>
Replace the content of DragAndDropWindow.uss
with the following:
.slot { width: 80px; height: 80px; margin: 5px; background-color: rgb(255, 255, 255); border-top-radius: 10px; border-top-left-radius: 10px; border-bottom-left-radius: 10px; border-top-right-radius: 10px; border-bottom-right-radius: 10px; } .slot_row { flex-direction: row; } .object { width: 50px; height: 50px; position: absolute; left: 20px; top: 20px; border-radius: 30px; background-color: rgb(0, 0, 0); }
To define the drag-and-drop behavior, extend the PointerManipulator
class and define the logic. Write a constructor to set target
and store a reference to the root of the visual tree. Write four methods that act as callbacks for PointerDownEvent
s, PointerMoveEvent
s, PointerUpEvent
s, and PointerCaptureOutEvent
s. Implement RegisterCallbacksOnTarget()
and UnregisterCallbacksOnTarget()
to register and un-register these four callbacks from target
.
In the Editor
folder, create another C# file named DragAndDropManipulator.cs
.
Replace the content of DragAndDropManipulator.cs
with the following:
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UIElements; public class DragAndDropManipulator : PointerManipulator { // Write a constructor to set target and store a reference to the // root of the visual tree. public DragAndDropManipulator(VisualElement target) { this.target = target; root = target.parent; } protected override void RegisterCallbacksOnTarget() { // Register the four callbacks on target. target.RegisterCallback<PointerDownEvent>(PointerDownHandler); target.RegisterCallback<PointerMoveEvent>(PointerMoveHandler); target.RegisterCallback<PointerUpEvent>(PointerUpHandler); target.RegisterCallback<PointerCaptureOutEvent>(PointerCaptureOutHandler); } protected override void UnregisterCallbacksFromTarget() { // Un-register the four callbacks from target. target.UnregisterCallback<PointerDownEvent>(PointerDownHandler); target.UnregisterCallback<PointerMoveEvent>(PointerMoveHandler); target.UnregisterCallback<PointerUpEvent>(PointerUpHandler); target.UnregisterCallback<PointerCaptureOutEvent>(PointerCaptureOutHandler); } private Vector2 targetStartPosition { get; set; } private Vector3 pointerStartPosition { get; set; } private bool enabled { get; set; } private VisualElement root { get; } // This method stores the starting position of target and the pointer, // makes target capture the pointer, and denotes that a drag is now in progress. private void PointerDownHandler(PointerDownEvent evt) { targetStartPosition = target.transform.position; pointerStartPosition = evt.position; target.CapturePointer(evt.pointerId); enabled = true; } // This method checks whether a drag is in progress and whether target has captured the pointer. // If both are true, calculates a new position for target within the bounds of the window. private void PointerMoveHandler(PointerMoveEvent evt) { if (enabled && target.HasPointerCapture(evt.pointerId)) { Vector3 pointerDelta = evt.position - pointerStartPosition; target.transform.position = new Vector2( Mathf.Clamp(targetStartPosition.x + pointerDelta.x, 0, target.panel.visualTree.worldBound.width), Mathf.Clamp(targetStartPosition.y + pointerDelta.y, 0, target.panel.visualTree.worldBound.height)); } } // This method checks whether a drag is in progress and whether target has captured the pointer. // If both are true, makes target release the pointer. private void PointerUpHandler(PointerUpEvent evt) { if (enabled && target.HasPointerCapture(evt.pointerId)) { target.ReleasePointer(evt.pointerId); } } // This method checks whether a drag is in progress. If true, queries the root // of the visual tree to find all slots, decides which slot is the closest one // that overlaps target, and sets the position of target so that it rests on top // of that slot. Sets the position of target back to its original position // if there is no overlapping slot. private void PointerCaptureOutHandler(PointerCaptureOutEvent evt) { if (enabled) { VisualElement slotsContainer = root.Q<VisualElement>("slots"); UQueryBuilder<VisualElement> allSlots = slotsContainer.Query<VisualElement>(className: "slot"); UQueryBuilder<VisualElement> overlappingSlots = allSlots.Where(OverlapsTarget); VisualElement closestOverlappingSlot = FindClosestSlot(overlappingSlots); Vector3 closestPos = Vector3.zero; if (closestOverlappingSlot != null) { closestPos = RootSpaceOfSlot(closestOverlappingSlot); closestPos = new Vector2(closestPos.x - 5, closestPos.y - 5); } target.transform.position = closestOverlappingSlot != null ? closestPos : targetStartPosition; enabled = false; } } private bool OverlapsTarget(VisualElement slot) { return target.worldBound.Overlaps(slot.worldBound); } private VisualElement FindClosestSlot(UQueryBuilder<VisualElement> slots) { List<VisualElement> slotsList = slots.ToList(); float bestDistanceSq = float.MaxValue; VisualElement closest = null; foreach (VisualElement slot in slotsList) { Vector3 displacement = RootSpaceOfSlot(slot) - target.transform.position; float distanceSq = displacement.sqrMagnitude; if (distanceSq < bestDistanceSq) { bestDistanceSq = distanceSq; closest = slot; } } return closest; } private Vector3 RootSpaceOfSlot(VisualElement slot) { Vector2 slotWorldSpace = slot.parent.LocalToWorld(slot.layout.position); return root.WorldToLocal(slotWorldSpace); } }
To enable drag-and-drop in the custom window, instantiate it when the window opens.
In DragAndDropWindow.cs
, add the following to the CreateGUI()
method to instantiate the DragAndDropManipulator
class:
DragAndDropManipulator manipulator = new(rootVisualElement.Q<VisualElement>("object"));
From the menu bar, select Window > UI Toolkit > Drag And Drop. In the opened custom Editor window, you can drag the object into any slot.
Did you find this page useful? Please give it a rating:
Thanks for rating this page!
What kind of problem would you like to report?
Thanks for letting us know! This page has been marked for review based on your feedback.
If you have time, you can provide more information to help us fix the problem faster.
Provide more information
You've told us this page needs code samples. If you'd like to help us further, you could provide a code sample, or tell us about what kind of code sample you'd like to see:
You've told us there are code samples on this page which don't work. If you know how to fix it, or have something better we could use instead, please let us know:
You've told us there is information missing from this page. Please tell us more about what's missing:
You've told us there is incorrect information on this page. If you know what we should change to make it correct, please tell us:
You've told us this page has unclear or confusing information. Please tell us more about what you found unclear or confusing, or let us know how we could make it clearer:
You've told us there is a spelling or grammar error on this page. Please tell us what's wrong:
You've told us this page has a problem. Please tell us more about what's wrong:
Thank you for helping to make the Unity documentation better!
Your feedback has been submitted as a ticket for our documentation team to review.
We are not able to reply to every ticket submitted.
When you visit any website, it may store or retrieve information on your browser, mostly in the form of cookies. This information might be about you, your preferences or your device and is mostly used to make the site work as you expect it to. The information does not usually directly identify you, but it can give you a more personalized web experience. Because we respect your right to privacy, you can choose not to allow some types of cookies. Click on the different category headings to find out more and change our default settings. However, blocking some types of cookies may impact your experience of the site and the services we are able to offer.
More information
These cookies enable the website to provide enhanced functionality and personalisation. They may be set by us or by third party providers whose services we have added to our pages. If you do not allow these cookies then some or all of these services may not function properly.
These cookies allow us to count visits and traffic sources so we can measure and improve the performance of our site. They help us to know which pages are the most and least popular and see how visitors move around the site. All information these cookies collect is aggregated and therefore anonymous. If you do not allow these cookies we will not know when you have visited our site, and will not be able to monitor its performance.
These cookies may be set through our site by our advertising partners. They may be used by those companies to build a profile of your interests and show you relevant adverts on other sites. They do not store directly personal information, but are based on uniquely identifying your browser and internet device. If you do not allow these cookies, you will experience less targeted advertising. Some 3rd party video providers do not allow video views without targeting cookies. If you are experiencing difficulty viewing a video, you will need to set your cookie preferences for targeting to yes if you wish to view videos from these providers. Unity does not control this.
These cookies are necessary for the website to function and cannot be switched off in our systems. They are usually only set in response to actions made by you which amount to a request for services, such as setting your privacy preferences, logging in or filling in forms. You can set your browser to block or alert you about these cookies, but some parts of the site will not then work. These cookies do not store any personally identifiable information.