Unity 드래그 앤 드롭 UI 가이드

이 문서는 Unity의 커스텀 에디터 창에서 드래그 앤 드롭 UI를 생성하는 방법을 설명합니다. 아래 예제를 통해 UI 툴킷을 활용하여 두 개의 에디터 창 간에 드래그 앤 드롭 기능을 구현하는 방법을 알아보겠습니다.

개요

이 예제에서는 두 개의 커스텀 에디터 창을 생성하고, 프로젝트 창에서 에셋을 이 창으로 드래그할 수 있는 방법을 보여줍니다. 사용자는 같은 에셋을 한 창에서 다른 창으로 이동할 수도 있습니다.

선행 조건

이 가이드는 Unity 에디터, UI 툴킷, C# 스크립팅에 익숙한 개발자를 위한 것입니다. 시작하기 전에 다음 요소들을 숙지하십시오:

  • UI 빌더
  • USS 및 UXML
  • 드래그 앤 드롭 이벤트
  • 포인터 이벤트
  • UnityEditor.DragAndDrop

UI 정의

각 에디터 창의 콘텐츠는 빌트인 시각적 요소가 있는 UXML 파일로 정의됩니다. 각 창에는 배경, 헤더, 드롭 영역, 텍스트가 포함되어 있습니다. USS 파일을 통해 시각적 요소의 스타일을 지정합니다.

UXML 파일 생성

DragAndDrop.uxml 파일에 아래와 같은 내용을 포함시킵니다.

<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">
    <ui:VisualElement class="background">
        <ui:VisualElement class="header">
            <ui:Label text="Drag And Drop Sample" display-tooltip-when-elided="true" class="header__label" />
        </ui:VisualElement>
        <ui:VisualElement class="drop-area">
            <ui:Label text="Drag an asset here..." display-tooltip-when-elided="true" class="drop-area__label" />
        </ui:VisualElement>
    </ui:VisualElement>
</ui:UXML>

USS 파일 생성

DragAndDrop.uss 파일에 아래와 같이 스타일을 지정합니다.

.background {
    flex-grow:1;
    background-color: rgba(30, 30, 30, 255);
}

.header {
    align-items: center;
    margin-left:10px;
    margin-right:10px;
    margin-top:10px;
    margin-bottom:10px;
    padding-left:5px;
    padding-right:5px;
    padding-top:5px;
    padding-bottom:5px;
    background-color: rgba(112, 128, 144, 255);
    border-width:2px;
    border-color: rgba(211, 211, 211, 255);
}

.header__label {
    font-size:18px;
    color: rgba(255, 255, 255, 255);
}

.drop-area {
    flex-grow:1;
    align-items: center;
    justify-content: center;
    margin: 10px;
    padding: 5px;
    background-color: rgba(112, 128, 144, 255);
    border-width:2px;
    border-color: rgba(211, 211, 211, 255);
    border-radius:20px;
}

.drop-area--dropping {
    opacity:0.4;
    background-color: rgba(0, 100, 0, 255);
}

.drop-area__label {
    -unity-font-style: italic;
    color: rgba(255, 255, 255, 255);
}

매니퓰레이터 생성

드래그 앤 드롭 기능을 위해 매니퓰레이터를 생성하여 이벤트 콜백을 등록합니다. 아래 코드 스니펫은 C#에서 DragAndDropManipulator 클래스를 정의한 것입니다.

using UnityEngine;
using UnityEditor;
using UnityEngine.UIElements;

namespace Samples.Editor.General
{
    public partial class DragAndDropWindow
    {
        class DragAndDropManipulator : PointerManipulator
        {
            Label dropLabel;
            Object droppedObject = null;
            string assetPath = string.Empty;

            public DragAndDropManipulator(VisualElement root)
            {
                target = root.Q<VisualElement>(className: "drop-area");
                dropLabel = root.Q<Label>(className: "drop-area__label");
            }

            protected override void RegisterCallbacksOnTarget()
            {
                target.RegisterCallback<PointerDownEvent>(OnPointerDown);
                target.RegisterCallback<DragEnterEvent>(OnDragEnter);
                target.RegisterCallback<DragLeaveEvent>(OnDragLeave);
                target.RegisterCallback<DragUpdatedEvent>(OnDragUpdate);
                target.RegisterCallback<DragPerformEvent>(OnDragPerform);
            }

            protected override void UnregisterCallbacksFromTarget()
            {
                target.UnregisterCallback<PointerDownEvent>(OnPointerDown);
                target.UnregisterCallback<DragEnterEvent>(OnDragEnter);
                target.UnregisterCallback<DragLeaveEvent>(OnDragLeave);
                target.UnregisterCallback<DragUpdatedEvent>(OnDragUpdate);
                target.UnregisterCallback<DragPerformEvent>(OnDragPerform);
            }

            // 드래그 이벤트와 관련된 메서드들 정의
            void OnPointerDown(PointerDownEvent _) { /* ... */ }
            void OnDragEnter(DragEnterEvent _) { /* ... */ }
            void OnDragLeave(DragLeaveEvent _) { /* ... */ }
            void OnDragUpdate(DragUpdatedEvent _) { /* ... */ }
            void OnDragPerform(DragPerformEvent _) { /* ... */ }
        }
    }
}

에디터 창 생성

이제 두 개의 커스텀 에디터 창을 생성하고 각 창에 매니퓰레이터를 인스턴스화합니다. 아래 C# 스크립트 예제를 활용하세요.

using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;

namespace Samples.Editor.General
{
    public partial class DragAndDropWindow : EditorWindow
    {
        [SerializeField]
        VisualTreeAsset uxmlAsset;
        DragAndDropManipulator manipulator;

        readonly static Vector2 windowMinSize = new(300, 180);
        readonly static Vector2 windowAPosition = new(50, 50);
        readonly static Vector2 windowBPosition = new(450, 100);
        const string windowATitle = "Drag and Drop A";
        const string windowBTitle = "Drag and Drop B";

        [MenuItem("Window/UI Toolkit/Drag And Drop (Editor)")]
        public static void OpenDragAndDropWindows()
        {
            var windowA = CreateInstance<DragAndDropWindow>();
            var windowB = CreateInstance<DragAndDropWindow>();
            windowA.minSize = windowMinSize;
            windowB.minSize = windowMinSize;
            windowA.Show();
            windowB.Show();
            windowA.titleContent = new(windowATitle);
            windowB.titleContent = new(windowBTitle);
            windowA.position = new(windowAPosition, windowMinSize);
            windowB.position = new(windowBPosition, windowMinSize);
        }

        void OnEnable()
        {
            if (uxmlAsset != null)
            {
                uxmlAsset.CloneTree(rootVisualElement);
            }
            manipulator = new(rootVisualElement);
        }

        void OnDisable()
        {
            manipulator.target.RemoveManipulator(manipulator);
        }
    }
}

실행하기

  1. DragAndDropWindow.cs를 선택하고 DragAndDrop.xml을 인스펙터의 Uxml 에셋으로 드래그합니다.
  2. 메뉴에서 Window > UI Toolkit > Drag and Drop (Editor)을 선택합니다.
  3. 두 개의 Drag and Drop 창이 열리며, 프로젝트 창에서 에셋을 드래그하여 이 창의 드롭 영역에 놓을 수 있습니다.

추가 리소스

  • 커스텀 에디터 창 내에 드래그 앤 드롭 UI 만들기
  • 드래그 앤 드롭 이벤트
  • 커스텀 에디터 창 내부에 드래그 앤 드롭 UI 생성
  • 전환 이벤트 만들기

이 문서를 통해 Unity에서 드래그 앤 드롭 UI를 성공적으로 구현할 수 있기를 바랍니다. 필요시 추가 리소스를 참고하세요.

Read more

Unity 매뉴얼 스크립팅 API 해설

이 문서는 Unity의 매뉴얼 스크립팅 API에 대한 간단한 해설과 활용 예제들을 포함하고 있습니다. Unity는 게임 개발 플랫폼으로, 스크립팅 API를 통해 게임의 다양한 기능을 제어하고 수정할 수 있습니다. 버전 Unity 스크립팅 API는 여러 버전으로 제공됩니다. 주의 깊게 선택하여 사용하는 것이 중요합니다. 버전 설명 2023.2 최신 기능 및 버그 수정이 추가됨

By 이재협/실장/시스템개발실/PHYSIA

Unity 매뉴얼 스크립팅 API 설명서 해설

이 문서는 Unity의 매뉴얼 스크립팅 API에 대한 정보를 제공하며, 버전에 따라 다르게 적용되는 내용들을 설명합니다. 본 문서에서는 주요 내용을 간단히 정리하고 활용 가능 예제를 통해 이해를 돕겠습니다. 기본 개념 Unity에서 스크립팅 API는 게임 오브젝트와 그들의 동작을 제어하기 위한 강력한 도구입니다. 이를 통해 게임의 로직, 물리 엔진, 애니메이션 및 사용자 인터페이스를

By 이재협/실장/시스템개발실/PHYSIA

Unity 스크립팅 API 가이드

이 문서는 Unity의 스크립팅 API에 대해 설명합니다. Unity는 게임 개발을 위한 인기 있는 엔진으로, 강력한 스크립팅 기능을 제공합니다. 이 가이드는 Unity에서 스크립트를 작성하고 사용하는 방법을 이해하는 데 도움을 드립니다. 목차 * Unity 스크립팅 소개 * 기본 스크립트 생성 * 스크립트 사용 예제 * 응용 프로그램 * 참고 자료 Unity 스크립팅 소개 Unity는 C# 프로그래밍 언어를

By 이재협/실장/시스템개발실/PHYSIA