Reputation: 967
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.
Upvotes: 6
Views: 17526
Reputation: 967
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.
Upvotes: 3
Reputation: 2167
I do it like this. Its a lamba expression .
btn.onClick.AddListener(() =>
{
Debug.Log("IT WORKS");
// Just handle the button clikc inside here
});
or you could try a completely different aproach :
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class TapOnNumber : MonoBehaviour, IPointerClickHandler {
public void OnPointerClick(PointerEventData e)
{
//HandleClicks here
}
Upvotes: 1
Reputation: 197
What you are trying to do here is add the callback at runtime. If you want to add the callback at design time you should instead click the little plus in the bottom right section of the On Click section in the editor and then select which object that should handle the callback and which function the button should call
Upvotes: 1