1
\$\begingroup\$

I don't seem to be able to make a reference to a Button inside a menu prefab.

My menu prefab consists of a panel and the panel has 4 buttons.

I added

public GameObject prefabMenu;

in my code and drag and dropped the prefab in the Unity Editor to it.

When my scene is starting (Start() method) I instantiate this prefab into a GameObject like this:

panelMenu = Instantiate(prefabMenu, canvas.transform);

after that I try to refer one of the buttons with this line and set an onClick listener:

btnResume = panelMenu.transform.Find("BtnResume").GetComponent<Button>();
btnResume.onClick.AddListener(() => Log.I("Working"));

The log method however doesn't not get called when I click on the button (I checked and the btnResume is not null).

I appreciate any help on this. Thank you.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Just to be sure, you have the Eventsystem in your scene, correct? \$\endgroup\$
    – Zibelas
    Mar 26, 2021 at 12:22
  • \$\begingroup\$ You don't have Raycast on the UI stopping the button from being clicked, right? \$\endgroup\$ Mar 26, 2021 at 16:21
  • \$\begingroup\$ @Zibelas No, I didn't have. I added it and now it works. Thank you so much! \$\endgroup\$ Mar 26, 2021 at 19:57

2 Answers 2

0
\$\begingroup\$

1- first check is your event system object present in the Hierarchy if yes then create a button check its working or not if working fine then its your button problem either it can be due Raycast or some other UI object over that button.

2- second try is that assign a function from editor to that button if its working then your event subscribing (onclick event) is in problem..

\$\endgroup\$
0
\$\begingroup\$

To have click events in a prefab try to use IPointerClickHandler interface.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .