skyerenauld
skyerenauld

Reputation: 41

Unity OnClick.AddListener Stopped Working

I am building a card matching game. On start, the game generates 16 buttons (the cards) and each button is given a listener to respond when clicked. Now, up until yesterday this was working perfectly.

Today I tried to add a particle emitter to the scene (made no changed to the code). When I ran the scene to test the emitter, the buttons wouldn't work. I removed the emitter but the problem persisted. I checked the buttons in the inspector and no onClick event has been added to any of them.

No matter what I do I can't seem to get it to add the onClick to the buttons anymore.

Here is my code:

      void Start()
        {
            GetButtons();
            AddListeners();
            AddGamePuzzles(); 
            ShuffleSprites(gamePuzzles);
    
            gameGuesses = gamePuzzles.Count / 2;
        }
    
        void GetButtons()
        {
            GameObject[] BtnObjects = GameObject.FindGameObjectsWithTag("PuzzleButton");
    
            for(int i = 0; i < BtnObjects.Length; i++)
            {
                btns.Add(BtnObjects[i].GetComponent<Button>());
                btns[i].image.sprite = bgImage; 
            }
        }
    
        void AddListeners()
        {
            foreach (Button btn in btns)
            {
                btn.onClick.AddListener(() => PickAPuzzle());
            }
        }

Any assistance would be greatly appreciated. I've been pulling my hair out for hours now.

Upvotes: 1

Views: 1709

Answers (1)

skyerenauld
skyerenauld

Reputation: 41

Firstly I would like to say thank you to those who took the time to try assist me with answers.

The problem turned out to be my own stupidity. I accidentally disabled the Graphic Raycaster on my Canvas, making it impossible to click the buttons. Re-enabling the Raycaster fixed the issue immediately.

Something I learnt out of all this: When you add a listener to a button while the game is running, that listener will not be displayed in the inspector, but it is there.

Upvotes: 3

Related Questions