- Home /
button.onClick.AddListener(method); NOT Working
So I'm creating a very basic menu with 3 buttons. I had the buttons working earlier today to the point that they would do what they should have. Unfortunately, because of some tweaking I did, the onClick function doesn't seem to be working for me. I would love some insight, thank you!
Code: using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI;
public class PauseUI : MonoBehaviour {
private Component[] buttons, screens;
private Canvas pauseMenu;
private Button resumeGame, exitGame;
private Camera characterCam, pauseCam;
void Start ()
{
characterCam = GameObject.Find ("MainCamera").GetComponent<Camera>();
pauseCam = this.GetComponent<Camera> ();
buttons = GetComponentsInChildren<Button> ();
screens = GetComponentsInChildren<Canvas> ();
foreach (Button button in buttons) {
if (button.name == "ResumeGame") {
resumeGame = button;
}
if (button.name == "ExitGame") {
exitGame = button;
}
}
foreach (Canvas canvas in screens) {
if (canvas.name == "PauseMenu") {
pauseMenu = canvas;
}
}
characterCam.enabled = true;
pauseCam.enabled = false;
pauseMenu.enabled = false;
}
// Update is called once per frame
void Update ()
{
if (Input.GetKeyDown (KeyCode.Escape)) {
pauseMenu.enabled = true;
characterCam.enabled = false;
pauseCam.enabled = true;
}
resumeGame.onClick.AddListener (ResumeGame);
}
void ResumeGame(){
Debug.Log ("ResumeGame has been clicked!");
pauseMenu.enabled = false;
characterCam.enabled = true;
pauseCam.enabled = false;
}
}
You are adding a new listener to the button EVERY FRA$$anonymous$$E
Have you checked the answer I gave here? https://answers.unity.com/questions/1402544/so-my-buttons-stop-working.html
Answer by upasnavig90 · Mar 03, 2018 at 09:21 AM
try this: resumeGame.onClick.AddListener (()=>ResumeGame);
This won't compile.
If you meant
resumeGame.onClick.AddListener (()=>ResumeGame());
This will be worse than resumeGame.onClick.AddListener (ResumeGame);
because you create a useless lambda function.