I am creating a new gameobject from c# and trying to execute a script when clecked. here is the code.
public void createButton(){
GameObject kGO = new GameObject ();
kGO.transform.parent = kCanvas.transform;
kGO.AddComponent<Image>();
Button btn = kGO.AddComponent<Button>();
btn.onClick.AddListener(onButtonClick);
}
public void onButtonClick(){
Debug.Log ("clicked");
}
but this script is not working, there is not any script attached to the button. .
I have tried these also
btn.onClick.AddListener(() => {onButtonClick()});
or
btn.onClick.AddListener(() => {onButtonClick();});
or
btn.onClick.AddListener(() => onButtonClick());
But nothing is working.
To insert a button, right click in the Scene Hierarchy and go to Create → UI → Button. If you do not have an existing Canvas and an EventSystem, Unity will automatically create one for you, and place the button inside the Canvas as well.
Use UnityEvent. AddListener to extend the onClick click events. The added UnityAction is called when the Button press is released. A Button can have multiple listeners.
I have updated unity to 5.1.2, now it is working fine. But it still do not reflect in the UI, some people are saying that non persistent unity events does not reflect in the UI, I guess that is true.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With