- Home /
Pass more than one argument through a UI button?
I've looked around for an answer to this for a while now, but I couldn't find anything that was up to date and not super duper overly complicated. I have a shop system with purchase buttons, and I have a function I want to run when one of those buttons is clicked. There are quite a few arguments I would LIKE to have on the function but the very least amount I can think of is 2, the price and the gameobject prefab it'll spawn when the purchase button is clicked. The issue is, if I try and get the button to run the function, it won't work unless there is only one argument. I COULD just make a separate function for every single object but obviously that would be very inefficient. I've seen people talk about making their own events with the button or something but couldn't really find a good explanation, how should I go about doing this? Thanks.
Answer by Bunny83 · Dec 29, 2019 at 07:15 PM
Well, Unity's UnityEvent type can only store one argument in the persistent call list per call. So there's no way with the current system to specify more than one serialized argument per call. Though I wou'dn't recommend to encode the price of an item in the method binding of a button. This is IMO the wrong approach to begin with. Each item / object you want to buy should be represented either through a gameobject / prefab with a Monobehaviour script which stores the relevant information for the item in the item itself, or you might use a scriptableobject which stores all the relevant data for a certain purchase item (price / prefab referenec / ...) and just link that scriptable object instance to your button. The method that is called can use all the information on the object we pass as parameter.
Thanks, I did something like this and it's working well.
Answer by unity_ek98vnTRplGj8Q · Dec 30, 2019 at 04:22 PM
To expand on Bunny's answer, in case you needed help visualizing this
//Attach one of these to each shop item you have
public class ShopItem{
//You can modify these on a per-item basis
public int itemCost;
public GameObject prefab;
//Attach this to your button click event
public void OnShopButtonClick(){
DoStuff(itemCost, prefab);
}
//The function you want to be called when the button is clicked
public void DoStuff(int cost, GameObject item){
//Do stuff
}
}
Your answer
Follow this Question
Related Questions
Create a new event for Button UI using script. 1 Answer
calling a function when any variable in an array changes 1 Answer
Create GUI based on an array 2 Answers
Make use of a button in a drop down menu? 0 Answers
Two Times Button - Looping 1 Answer