Valar Morghulis
Valar Morghulis

Reputation: 687

How to disable button OnClick when drag on the screen with OnMouseDrag in Unity

I'm using OnMouseDrag() to change the camera view of the object on the screen. The code is like:

void OnMouseDrag() {    
if (isGameOver) {           
return;         
}       
float rotSpeed = GameConst.rotateSpeed * 20.0f ;
float rotX = Input.GetAxis("Mouse X") * rotSpeed * Mathf.Deg2Rad;
float rotY = Input.GetAxis("Mouse Y") * rotSpeed * Mathf.Deg2Rad;
transform.RotateAround(Vector3.up, -rotX);      transform.RotateAround(Vector3.right - Vector3.forward, -rotY);
}

Then I use button.OnClick().AddListerner() to attach a function when the button is clicked.

The problem is, everytime when I finish the drag, if the mouse up position is in the button region, the button would call the OnClick() function too. How can I disable OnClick() when it's a just a drag action?

Upvotes: 5

Views: 5708

Answers (2)

Everts
Everts

Reputation: 10721

Use the IDragHandler to perform the drag and set a flag that you have been dragging. https://docs.unity3d.com/ScriptReference/EventSystems.IDragHandler.html

Then use the IPointerUpHandler to call the action if the flag is not on. Also, reset the flag whatever happened:

public class DragMe : MonoBehaviour, IBeginDragHandler, IPointerUpHandler
{
    private bool isDragging = false;


    public void OnBeginDrag(PointerEventData data)
    {
        this.isDragging = true;
    }
    public void OnPointerUp(PointerEventData eventData)
    {
       if(this.isDragging == false){ Invoke();}
       this.isDragging = false;
    }
}

Upvotes: 3

Fredrik
Fredrik

Reputation: 5108

If you just want to solve the problem I guess you could just add a boolean isDragging which you set to true when you enter OnMouseDrag and false when OnMouseUp. And then you wrap your buttons listener method with if (!isDragging) or equivalent.

There might be a more technical solution based on the behaviour of MonoBehaviour that I'm not aware of.

Upvotes: 2

Related Questions