Solved: Cant get onclick assignet to prefabs button

Hi

I have this code to add onclick listener and method call to button in prefab.

Everything else works in this code, except onclick listener and method call. With this code, i get red button with text “labelText” and it clicks visually. It does not run myMethod and while running, checking from inspector it does not have onclicks.

    putikka = item.GetComponent<Button>();
    if (putikka != null)
    {
       Debug.Log("Button found");
       putikka.GetComponent<Button>().onClick.AddListener(() => { myMethod(data); });
       putikka.GetComponentInChildren<Text>().text = "labelText";
       putikka.GetComponent<Button>().image.color = Color.red;
       putikka.GetComponent<Button>().interactable = true;
   }

This is alternative line i have tried with similar success…

putikka.GetComponent<Button>().onClick.AddListener(delegate () { myMethod(data); });

So i can clearly access the button cause color and interactble can be changed. It even dont give me any errors to help solve the problem.

What am i doing wrong?

Solved.

I was sure when the problem occurred, that i am an idiot, but i just could not find the point, where i was an idiot. But i found it. I was trying to add addListener directly to prefab. Otherwise it was fine by text objects and images but addListener seems not to work that way. So what i did, i renamed prefabs individually when inserting them in my content and i renamed button also. Then i called another method with name as argument, find the the prefab and the button and added addListener. And it works. Also learned great many things about been an idiot and how make code. Lesson learned! :slight_smile: