- Home /
Button onClick is called when added to the Listener
I try in C# Script too add a method to a Button for the onClick Event. I do this in OnMouseDown of a script that is connected to my gameobject like this:
Button FeedButton = GameObject.Find("/Canvas/MyButton").GetComponent<Button>();
FeedButton.onClick.RemoveAllListeners();
FeedButton.onClick.AddListener(() => { ClickedButton(); });
So far it works but there is one probem: ClickedButton() is called in the moment when I add it to the listener even though the button wasn't clicked that moment...How can this happen?
Answer by Tourist · Feb 03, 2015 at 04:54 PM
The game object you are talking about is the one the button is in? If so ClickedButton is called because the event is sent on mouse released.
You should either : - change the moment the callback is added. - invalidate the first call using a boolean.
I think the 1st proposition is the right one. I don't know what you are tring to do but this seems ill-designed.
Answer by grka · Feb 03, 2015 at 06:21 PM
I found a solution by now. The problem was that when I click on my gameobject I move the canvas into the cameraview in the onmousedown method. when I release the mouse button the canvas was already displayed and the mouse click event was sent to the button. I think this is a bug in unity. I made a workaround that I wait a second before I the AddListener
void OnMouseDown()
{
MovingCanvasInView();
StartCoroutine(AddListener());
}
IEnumerator AddListener()
{
yield return new WaitForSeconds(1);
FeedButton.onClick.AddListener(FeedNow);
yield break;
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613182200im_/https://answers.unity.com/themes/thub/images/avi.jpg)