- Home /
Passing object as an argument to a System.Action
I am trying to create a feature that will allow developers to create a button and pass object as arguments.
Following set up works but I want to take this to new level where user can define object as an argument for the buttonAction
public Button AddButton (string buttonLabel, System.Action buttonAction)
{
GameObject newButton;
newButton = Instantiate (ButtonTemplate); //ButtonTemplate prefab
//Change button settings
newButton.name = buttonLabel;
newButton.GetComponentInChildren<Text> ().text = buttonLabel;
Button newButtonComponent = newButton.GetComponentInChildren<Button>();
//Add a listener for the button action when it is clicked
newButtonComponent.onClick.AddListener ( () => buttonAction ());
return newButtonComponent;
}
I am getting an error whenever I try to do this:
public Button AddButton (string buttonLabel, System.Action<object> buttonAction, object args)
{
//..........same stuff
//Add a listener for the button action when it is clicked
newButtonComponent.onClick.AddListener ( (args) => buttonAction (args));
return newButtonComponent;
}
error CS0136: A local variable named args' cannot be declared in this scope because it would give a different meaning to
args', which is already used in a `parent or current' scope to denote something else
I'm not sure, but I think you want to remove the ', object args' at the end of your method parameters. Sinse you are setting the listener, you are not invoking the action and thus you don't need to send any arguments...
The error (CS0136) you get is because 'args' (declared in the lambda expresson) hides 'args' (declared as a method parameter).
I'm not sure if it would work after you remove this, but this error should at least be gone.
EDIT: This will probably still not work as the onClick of a button doesn't accepts listeners with a parameter I believe. So if you ins$$anonymous$$d want to send the args that you gave as parameter, I think changing '(args)' to '()' in the lambda expression ins$$anonymous$$d might work.
Like this
newButtonComponent.onClick.AddListener( () => buttonAction(args));
Answer by atul-s-morey · Jul 16, 2015 at 01:19 PM
The answer is as simple as
public Button AddButton (string buttonLabel, System.Action<object> buttonAction, object args)
{
//..........same stuff
//Add a listener for the button action when it is clicked
newButtonComponent.onClick.AddListener ( () => buttonAction (args));
return newButtonComponent;
}
To take this one step further...
public Button AddButton (string buttonLabel, System.Action<object[]> buttonAction, params object args)
{
//..........same stuff
//Add a listener for the button action when it is clicked
newButtonComponent.onClick.AddListener ( () => buttonAction (args));
return newButtonComponent;
}
Now you have n number of arguments