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?
Answer by Jarpitskij · Oct 01, 2020 at 07:45 AM
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! :)
Your answer
Follow this Question
Related Questions
How to use one button to play different audio for different Targets? 0 Answers
button function on unity5 1 Answer
Next and Back Button? 0 Answers
Unity 5 - How to tell two prefabs apart? 1 Answer
OnClick() event script from a prefab 0 Answers