Problem with CreateButton.GetComponent<Button>().onClick.AddListener(() => { Dialog(); });

Hello, I have a problem with :
CreateButton.GetComponent().onClick.AddListener(() => { Dialog(); });
Does’t add function to a button.

    public void CreateDialogButton(string ButtonText, int id, DialogTopicVoid Dialog)
    {

        CreateButton = Instantiate(DialogButton);
        CreateButton.transform.parent = DialogWindowPanel.transform;
        if( id == 0 )
        {

            PosY = 85;

        }
        else
        {

            PosY = PosY - 30;

        }
        CreateButton.GetComponent<RectTransform>().localPosition = new Vector3( PosX, PosY, PosZ );
        CreateButton.GetComponent<RectTransform>().sizeDelta = new Vector2( SizeX, SizeY );
         CreateButton.GetComponentInChildren<Text>().text = ButtonText;
        CreateButton.name = ButtonText;
        CreateButton.GetComponent<Button>().onClick.AddListener(() => { Dialog(); });
     
    }

Code tags please.

What does happen when you click the button created by this code?

Note that runtime listeners will not show up in the inspector.

Nothing happens

I had trouble assigning onClick listeners within a loop, and found that separating the assignment of the listener fixed my issue. I’m not familiar with ‘DialogTopicVoid’ and assigning methods this way, but what if you did something like:

public void CreateDialogButton(string ButtonText, int id, DialogTopicVoid Dialog) {
    CreateButton = Instantiate(DialogButton);
    CreateButton.transform.parent = DialogWindowPanel.transform;
   
    PosY = (id == 0) ? 85 : PosY - 30;

    CreateButton.GetComponent<RectTransform>().localPosition = new Vector3( PosX, PosY, PosZ );
    CreateButton.GetComponent<RectTransform>().sizeDelta = new Vector2( SizeX, SizeY );
    CreateButton.GetComponentInChildren<Text>().text = ButtonText;
    CreateButton.name = ButtonText;

    AssignDialog(CreateButton.GetComponent<Button>(), Dialog());
}

public AssignDialog(Button btn, DialogTopicVoid dialog) {
    btn.onClick.AddListener(() => dialog);
}

Doesn’t works :frowning:
DialogTopicVoid is a delegate void because the function is transmitted from another script but if I try use function from this scripts it’s the same.

Someone help ?

So, I’ve tried all the methods suggested by you guys, and all of them works. So, I think your problem lies elsewhere. Is your scene correctly set up? Is there an EventSystem in your scene? If there isn’t there won’t be any click events generated.