- Home /
How to disable button OnClick when drag on the screen with OnMouseDrag
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?
You could use RemoveListener in the On$$anonymous$$ouseDrag function
Answer by Aurel333 · Jan 27, 2017 at 04:43 PM
If your drag and OnClick functions are in the same script, you can add a bool variable that is set to true when on drag is called and set back to false when mouse button is released. It should look like this:
private bool isDragging = false;
void OnMouseDrag(){
isDragging = true
//Your code
}
void OnMouseUp(){
isDragging = false
}
Not working, I guess the OnClick()
executes after the On$$anonymous$$ouseUp()
.
Answer by Arkshija · Apr 29, 2019 at 04:26 PM
I had this problem with a draggable component because that object had to be at the same time clickable but when I was dragging the component the onClick listener also was executing when the drag ends, I did this to fix that:
public bool isClickable = true;
void Start{
GetComponent<Button>().onClick.AddListener(() => executeThis(isClickable));
}
void ExecuteThis (bool isClickable){
if( isClickable){
// Do something
}
}
public void OnBeginDrag(PointerEventData eventData)
{
isClickable = false;
}
public void OnEndDrag(PointerEventData eventData)
{
isClickable = true;
}
Your answer
Follow this Question
Related Questions
OnMouseUp() Click Display Effect. 1 Answer
Click and Drag Camera 3 Answers
Instantiate and Scale with Mouse Click. 1 Answer
GUI Repeatbutton up? 1 Answer
right mouse down on a gameObject 2 Answers