IDragHandler

interface in UnityEngine.EventSystems


实现接口:IEventSystemHandler

切换到手册

描述

要实现的接口(如果您希望接收 OnDrag 回调)。

using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

[RequireComponent(typeof(Image))] public class DragMe : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler { public bool dragOnSurfaces = true;

private GameObject m_DraggingIcon; private RectTransform m_DraggingPlane;

public void OnBeginDrag(PointerEventData eventData) { var canvas = FindInParents<Canvas>(gameObject); if (canvas == null) return;

// We have clicked something that can be dragged. // What we want to do is create an icon for this. m_DraggingIcon = new GameObject("icon");

m_DraggingIcon.transform.SetParent(canvas.transform, false); m_DraggingIcon.transform.SetAsLastSibling();

var image = m_DraggingIcon.AddComponent<Image>();

image.sprite = GetComponent<Image>().sprite; image.SetNativeSize();

if (dragOnSurfaces) m_DraggingPlane = transform as RectTransform; else m_DraggingPlane = canvas.transform as RectTransform;

SetDraggedPosition(eventData); }

public void OnDrag(PointerEventData data) { if (m_DraggingIcon != null) SetDraggedPosition(data); }

private void SetDraggedPosition(PointerEventData data) { if (dragOnSurfaces &amp;&amp; data.pointerEnter != null &amp;&amp; data.pointerEnter.transform as RectTransform != null) m_DraggingPlane = data.pointerEnter.transform as RectTransform;

var rt = m_DraggingIcon.GetComponent<RectTransform>(); Vector3 globalMousePos; if (RectTransformUtility.ScreenPointToWorldPointInRectangle(m_DraggingPlane, data.position, data.pressEventCamera, out globalMousePos)) { rt.position = globalMousePos; rt.rotation = m_DraggingPlane.rotation; } }

public void OnEndDrag(PointerEventData eventData) { if (m_DraggingIcon != null) Destroy(m_DraggingIcon); }

static public T FindInParents<T>(GameObject go) where T : Component { if (go == null) return null; var comp = go.GetComponent<T>();

if (comp != null) return comp;

Transform t = go.transform.parent; while (t != null &amp;&amp; comp == null) { comp = t.gameObject.GetComponent<T>(); t = t.parent; } return comp; } }

公共函数

OnDrag当发生拖动时,每次移动光标时都会调用此函数。
Copyright © 2023 Unity Technologies
优美缔软件(上海)有限公司 版权所有
"Unity"、Unity 徽标及其他 Unity 商标是 Unity Technologies 或其附属机构在美国及其他地区的商标或注册商标。其他名称或品牌是其各自所有者的商标。
公安部备案号:
31010902002961