0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[Unity] UIをドラッグで移動させる

Posted at

ドラッグ処理を毎回調べながら書いている気がするので、さっき書いたものをまとめておきます。

移動させたいGameObjectにこのスクリプトをアタッチすれば動くはず(ただしuGUI専用)。

RectTransformDragger.cs
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;

public class RectTransformDragger : MonoBehaviour, IDragHandler, IBeginDragHandler, IEndDragHandler
{
    // このコンポーネントがついているGameObjectのRectTransform
    [SerializeField]
    private RectTransform _myRectTransform;

    // ドラッグ中のときtrue
    public bool IsDragging { get; private set; } = false;

    // ドラッグ開始時/終了時の処理を他のスクリプトから登録できるようにする
    public UnityAction<PointerEventData> OnBeginDragAction { get; set; }
    public UnityAction<PointerEventData> OnEndDragAction { get; set; }

    public void OnValidate()
    {
        // RectTransformをあらかじめ取得しておく
        _myRectTransform = GetComponent<RectTransform>();
    }

    // ドラッグ開始時に呼ばれる関数
    public void OnBeginDrag(PointerEventData eventData)
    {
        IsDragging = true;
        OnBeginDragAction?.Invoke(eventData);
    }

    // ドラッグ中に呼ばれる関数
    public void OnDrag(PointerEventData eventData)
    {
        // オブジェクトの位置を更新
        _myRectTransform.localPosition = ScreenToLocalPosition(eventData.position);
    }

    // ドラッグ終了時に呼ばれる関数
    public void OnEndDrag(PointerEventData eventData)
    {
        OnEndDragAction?.Invoke(eventData);
        IsDragging = false;
    }

    // ScreenPositionをLocalPositionに変換する関数
    public Vector2 ScreenToLocalPosition(Vector2 screenPosition)
    {
        RectTransform parentRectTransfrom = _myRectTransform.parent as RectTransform;
        RectTransformUtility.ScreenPointToLocalPointInRectangle(parentRectTransfrom, screenPosition, Camera.main, out Vector2 result);
        return result;
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?