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);
}
}
You have to decide when you want this function to call, and then you'll pass in a parameter at that time. If you want to call it when the script is executed, you can just call LoadLevelByName(levelName);
and it'll run. If you want to do it when a button is clicked, you can add the script to a button's onClick();
and pass in the scene name you want to load when it's clicked.
Answer by VRAndAR · Jan 22, 2018 at 07:24 AM
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.
@VRAndAR, you are supposed to give solution, rather than just giving suggestions without any description or procedure.
He's not supposed to give a solution of any kind. If you expect everything co$$anonymous$$g from above, you'd better find another profession and stop developing games.
He took time to give you a hand and you reply that with arrogance. Shame on you.
Answer by Theinsanekiller · Sep 26, 2019 at 03:17 AM
Check here: https://answers.unity.com/questions/1288510/buttononclickaddlistener-how-to-pass-parameter-or.html
Your answer
![](https://koobas.hobune.stream/wayback/20220612101428im_/https://answers.unity.com/themes/thub/images/avi.jpg)