- Home /
Only want to detect button click event
Basically I want to detect button click event. This button is new Unity UI control. But in this I have one problem. When I click on button, one of my statement also execute at same time.
Following statements :
if(Input.GetMouseButtonDown(0)){
// code snippet
}
So code under if statement also gets executed, I want to stop this. I only want to run my button click code. At present button click code is running as well if statement code is running.
Please give me some suggestion in this.
Answer by M-Hanssen · Apr 13, 2016 at 01:30 PM
You can detect the current GUI object that is clicked by:
EventSystem.current.currentSelectedGameObject
So if you would do something like this, you could check id the button is selected and ignore the clickDown:
public GameObject ButtonGameObject;
protected void Update()
{
if (Input.GetMouseButtonDown(0) && EventSystem.current.currentSelectedGameObject != ButtonGameObject)
{
// code snippet
}
}
Make sure to add using UnityEngine.EventSystems;
on top of your script.
@$$anonymous$$. Hanssen, Thanks for your reply, I will check this and reply back to you.
Slight change to work with all Unity UGUI elements (button, toggle, etc):
bool buttonDown = Input.Get$$anonymous$$ouseButtonDown(0);
var currentSelection = EventSystem.current.currentSelectedGameObject;
if (currentSelection && currentSelection.GetComponent<IPointerDownHandler>() != null) {
buttonDown = false;
}
if(buttonDown){
//DO STUFF
}