- Home /
Attach a function to different buttons and pass different parameters
My game is about gathering resources by clicking on buttons( think of a clicker game ) I have several buttons that each would add different resource when clicked on ( wood, stone, gold, etc) So, they all basically do the same functionality but the difference is the resource and the amount.
I tried doing a function like this:
public void AddResource(ResourceType resource, int amount)
{
// Add the resource
// ResourceType is an enum or could be a class
}
But It didn't show up when I tried to attach it to the button, then I realised that a function with more than one parameter cannot be attached to a button in unity's editor, or a parameter like an enum or a class I think.
How can I solve that problem, or is there a better approach than what I'm trying to do?
Answer by Getsumi3 · Feb 11, 2020 at 01:12 PM
Hi @Abdo023
You're right.
then I realised that a function with more than one parameter cannot be attached to a button in unity's editor, or a parameter like an enum or a class I think.
An approach that I'll probably use is assigning events via script
Lets say you have a script that stores references to all your buttons. All you need is to assign to each button your function
Here is the code:
private void Start()
{
SetupButtons();
}
public void SetupButtons()
{
//if you assign a button
btn_wood.onClick.AddListener(()=>AddResource(resource.wood, 10));
//if you assign a gameobject with a button component
btn_wood.GetComponent<Button>().onClick.AddListener(()=>AddResource(resource.wood, 10));
//setup your other buttons
}