Button.onClick how to pass parameter?

A button in class UIManager, when the button click, how to pass params(such as scene name) to the method LoadLevelByName in class LevelManager .

public class UIManager : MonoBehaviour {

    [SerializeField]
    private Button _startButton;
void Start ()
    {
        _startButton.onClick.AddListener(LevelManager.Instance.GotoLevel);
	}
}

public class LevelManager : MonoBehaviour
{

    public static LevelManager Instance;
    public UnityAction GotoLevel;

    void Awake ()
    {
        if ( Instance == null )
        {
            Instance = this;
            DontDestroyOnLoad(this.gameObject);
        }
        else if ( Instance != null )
        {
            Destroy(this.gameObject);
        }
    }

    void Start ()
    {
        GotoLevel = () => LoadLevelByName();
    }
    public void LoadLevelByName (string levelName)
    {
        SceneManager.LoadScene(levelName);
    }
}

Check here:

I’m just gonna post the above answer here because it helped me out, and this way if people find this post they don’t have to go clicking through posts to get the answer.

Basically you need to add “delegate” in the AddListener method, and then add the method along with any passed parameters in brackets. Here’s how I did it for all 5 of my buttons.

        menuButtons[0].button.onClick.AddListener(delegate { StartGame(true,false); });
        menuButtons[1].button.onClick.AddListener(delegate { StartGame(false,false); });
        menuButtons[2].button.onClick.AddListener(delegate { StartGame(false,true); });
        menuButtons[3].button.onClick.AddListener(delegate { ToggleWindow(statsScreen); });
        menuButtons[4].button.onClick.AddListener(delegate { ToggleWindow(rulesScreen); });

Don’t forget the semicolon right after the method, i know it’s a bit hard to see there.

If your Method has only one argument, Then the argument can be passed as a parameter in the inspector itself.If it has more than one parameter then you should register to events such as the addListener Event in unity when the button is clicked.