ドラッグ処理を毎回調べながら書いている気がするので、さっき書いたものをまとめておきます。
移動させたい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;
}
}