- Home /
onClick listener not being added properly via script, but no errors
Hey everyone! I'm having a problem with the onClick.AddListener() function. It is not returning any errors, but it is not adding my listener properly. Here is the code i'm using:
void SetupReloadButton()
{
reloadButton = GetButton("ReloadButton");
reloadButton.onClick.AddListener(DoSomething);
}
public Button GetButton(string name)
{
GameObject go = GameObject.Find(name);
return go.GetComponent<Button>();
}
void DoSomething()
{
Debug.Log("Did something.");
}
I have used this same method of adding onClick listeners in other parts of my app and it works fine. There are a few things that distinguish this part of the app from the others, that might be helpful information as to why this isn't working:
I instantiate tiles dynamically, only when the scene is loaded. The scene already contains a canvas with the button I care about before instantiating these tiles, but objects are added to the scene only once the scene is loaded.
I wait for the scene to be loaded before I instantiate those objects. To do this I have a class that checks if the scene was loaded or not. If it is loaded, it creates the tiles. Here is that code:
void Awake() { dynamicBoardManager = Object.FindObjectOfType<DynamicBoardManager>(); gameManager = Object.FindObjectOfType<GameManager>(); SceneManager.sceneLoaded += OnSceneLoaded; } void OnDestroy() { SceneManager.sceneLoaded -= OnSceneLoaded; } void OnSceneLoaded(Scene scene, LoadSceneMode loadSceneMode) { dynamicBoardManager.CreateBoard(gameManager.currentWorld, gameManager.currentLevel); }
I recently overhauled how i'm building my scene (used to be static, is now dynamic) and when it was a static scene, it worked perfectly fine. So i'm scratching my head as to why this isn't working when it's dynamic, or at least why i'm not getting any errors!
Your help is much appreciated :)
I already found out what my problem is.... And i'll leave it here in case anyone else has a similar one, since I couldn't find a problem like $$anonymous$$e while searching.
When copying over the stuff from one scene to the next I forgot to copy over the EventSystem! So by adding an EventSystem to the scene, everything worked like I expected it to.
It was such a dumb mistake, but I still almost expect some kind of error or warning letting me know my scene doesn't contain an EventSystem if I try to add a listener to a button.
Your answer
Follow this Question
Related Questions
My onclick action listeners I attach to my buttons as I instantiate them only work once 1 Answer
How do I attach Right Click to an EventSystem listener? 1 Answer
Button onClick is called when added to the Listener 2 Answers
onclick.addlistener only works once 0 Answers
Weird behaviour when trying to dynamically create buttons 0 Answers