Unity 매뉴얼: 마우스 이벤트

Unity에서는 UI 툴킷을 사용하여 사용자 인터페이스(UI)를 생성할 수 있습니다. 이 문서에서는 마우스 이벤트에 대해 설명하고 예제를 제공합니다.

마우스 이벤트란?

마우스 이벤트는 사용자가 UI 요소와 상호작용할 때 발생하는 이벤트입니다. 여기에는 마우스를 움직이는 것, 버튼을 누르는 것 등이 포함됩니다. 모든 마우스 이벤트는 기본적으로 MouseEventBase 클래스를 상속합니다.

마우스 이벤트 목록

이벤트 이름 설명 트리클다운 지원 버블업 지원 취소 가능
MouseDownEvent 사용자가 마우스 버튼을 누를 때 전송됨 지원 지원 지원
MouseUpEvent 사용자가 마우스 버튼을 놓을 때 전송됨 지원 지원 지원
MouseMoveEvent 사용자가 마우스를 움직일 때 전송됨 지원 지원 지원
WheelEvent 사용자가 마우스 휠을 활성화할 때 전송됨 지원 지원 지원
MouseEnterWindowEvent 마우스가 창에 들어갈 때 전송됨 지원 지원 지원
MouseLeaveWindowEvent 마우스가 창에서 나갈 때 전송됨 지원 지원 지원
MouseEnterEvent 마우스가 요소 또는 그 자손에 들어갈 때 전송됨 지원 지원 지원
MouseLeaveEvent 마우스가 요소 또는 그 자손에서 나갈 때 전송됨 지원 지원 지원
MouseOverEvent 마우스가 요소에 들어갈 때 전송됨 지원 지원 지원
MouseOutEvent 마우스가 요소에서 나갈 때 전송됨 지원 지원 지원

마우스 이벤트의 고유한 프로퍼티

  1. button: 어떤 마우스 버튼이 눌렸는지 식별합니다. |정수|버튼| |---|---| |0|왼쪽 버튼| |1|오른쪽 버튼| |2|가운데 버튼|
  2. pressedButtons: 현재 눌린 마우스 버튼 조합을 식별합니다. |정수|버튼| |---|---| |1|왼쪽 버튼| |2|오른쪽 버튼| |4|가운데 버튼|
  3. modifiers: 누른 수정 키를 식별합니다. 예를 들어 Shift, Ctrl 또는 Alt 키가 있습니다.
  4. mousePosition: 패널 내 마우스 포지션을 반환합니다.
  5. localMousePosition: 대상 시각적 요소를 기준으로 좌표를 반환합니다.
  6. mouseDelta: 이전 마우스 이벤트와 현재 마우스 이벤트 간의 차이를 반환합니다.

예제

에디터 창 예제

아래의 예제에서는 마우스 커서가 요소 위로 이동하거나 마우스 버튼을 누를 때 콘솔에 메시지를 출력하는 버튼을 생성합니다.

using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;

// Open this in the Editor via the menu Window > UI ToolKit > Mouse Event Test Window
public class MouseEventTestWindow : EditorWindow
{
    [MenuItem("Window/UI Toolkit/Mouse Event Test Window")]
    public static void ShowExample()
    {
        MouseEventTestWindow wnd = GetWindow<MouseEventTestWindow>();
        wnd.titleContent = new GUIContent("Mouse Event Test Window");
    }
    public void CreateGUI()
    {
        // Add a few buttons
        for (int i = 0; i < 3; i++)
        {
            Button newElement = new Button { name = $"Button {i}", text = $"Button {i}" };
            newElement.style.flexGrow = 1;
            rootVisualElement.Add(newElement);
        }
        // Register mouse event callbacks
        rootVisualElement.RegisterCallback<MouseDownEvent>(OnMouseDown, TrickleDown.TrickleDown);
        rootVisualElement.RegisterCallback<MouseEnterEvent>(OnMouseEnter, TrickleDown.TrickleDown);
    }

    private void OnMouseDown(MouseDownEvent evt)
    {
        bool leftMouseButtonPressed = 0 != (evt.pressedButtons & (1 << (int)MouseButton.LeftMouse));
        bool rightMouseButtonPressed = 0 != (evt.pressedButtons & (1 << (int)MouseButton.RightMouse));
        bool middleMouseButtonPressed = 0 != (evt.pressedButtons & (1 << (int)MouseButton.MiddleMouse));
        Debug.Log($"Mouse Down event. Triggered by {(MouseButton)evt.button}.");
        Debug.Log($"Pressed buttons: Left button: {leftMouseButtonPressed} Right button: {rightMouseButtonPressed} Middle button: {middleMouseButtonPressed}");
    }

    private void OnMouseEnter(MouseEnterEvent evt)
    {
        VisualElement targetElement = (VisualElement)evt.target;
        Debug.Log($"Mouse is now over element '{targetElement.name}'");
    }
}

런타임 예제

아래의 예제는 게임 뷰에서 마우스 버튼을 누를 때 콘솔에 메시지를 출력하여, 어떤 버튼이 눌렸는지를 보여줍니다.

using UnityEngine;
using UnityEngine.UIElements;

public class MouseEventTestRuntime : MonoBehaviour
{
    void Start()
    {
        var root = GetComponent<UIDocument>().rootVisualElement;
        var newLabel = new Label("Move the mouse or press buttons to see the log output");
        newLabel.style.flexGrow = 1;
        root.Add(newLabel);
        root.RegisterCallback<MouseDownEvent>(OnMouseDown, TrickleDown.TrickleDown);
    }

    private void OnMouseDown(MouseDownEvent evt)
    {
        bool leftMouseButtonPressed = 0 != (evt.pressedButtons & (1 << (int)MouseButton.LeftMouse));
        bool rightMouseButtonPressed = 0 != (evt.pressedButtons & (1 << (int)MouseButton.RightMouse));
        bool middleMouseButtonPressed = 0 != (evt.pressedButtons & (1 << (int)MouseButton.MiddleMouse));

        VisualElement targetElement = (VisualElement)evt.target;
        Debug.Log($"Mouse Down event. Triggered by {(MouseButton)evt.button} over element '{targetElement.name}'");
        Debug.Log($"Pressed buttons: Left button: {leftMouseButtonPressed} Right button: {rightMouseButtonPressed} Middle button: {middleMouseButtonPressed}");
    }
}

이 문서에서 언급한 예제를 통해 Unity에서 마우스 이벤트를 처리하는 방법을 이해하고 활용할 수 있습니다. 추가적으로 물리적인 마우스 외에도 가상 마우스를 사용하는 방법이나, 다른 포인팅 기기의 처리를 포함할 수 있습니다.

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