トマシープが学ぶ

Unity/VR/AR/デザイン好きのミーハー 記事内容は自分用のメモです

uGUIの上でDragした値を取得する

EventSystems

EventSystemsという機能を使ってドラッグしたマウスの移動距離などを取得する

docs.unity3d.com

この記事の通り

qiita.com

適当なUI部品にEventSystemを付ける

f:id:bibinbaleo:20190827085041p:plain

そして下のスクリプトを付ける。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;


public class GetDragDelta : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
    private Vector2 deltaValue = Vector2.zero;

    public void OnBeginDrag(PointerEventData data)
    {
        deltaValue = Vector2.zero;
    }

    public void OnDrag(PointerEventData data)
    {
        deltaValue += data.delta;
        if (data.dragging)
        {

            Debug.Log("delta: " + deltaValue);

        }
    }

    public void OnEndDrag(PointerEventData data)
    {
        deltaValue = Vector2.zero;
    }
}

 

using UnityEngine.EventSystems;

using UnityEngine.UI;

を入れるのと

MonoBehaviorのあとに, IBeginDragHandler, IDragHandler, IEndDragHandler

を忘れない

 

これでdata.deltaにVector2でドラッグした移動距離が入る。

実際に動きはしない。

上のスクリプトいらなかった

Observable(Begin|End)DragTriggerというスクリプトが既にあるので、上のスクリプトの代わりにこれを付けて、UniRxでドラッグの量やドラッグ開始などをsubscribeできる。

qiita.com

ボタンみたいにサブスクライブ側だけ書けばいい。

上のスクリプト必要なかった。