- Home /
AddListener and UnityAction
In some examples UnityAction is used to call different functions like this:
UnityAction action;
action = Func1;
action();
action = Func2;
action();
void Func1()
{
}
void Func2()
{
}
I tried to use same approach with Button.OnClick by passing action to it and changing action somewhere else in the code like this:
void Start()
{
action = Func1;
button.onClick.AddListener(action);
}
void Update()
{
action = Func2;
}
But it seems that doesn't change the function called on button click. Is there a way without removing and re-adding listener?
Comment
Best Answer
Answer by homer_3 · Apr 19 at 11:21 PM
You could do something like
UnityAction action;
void Start()
{
action = Func1;
button.onClick.AddListener(MiddleMan);
}
void Update()
{
action = Func2;
}
void MiddleMan()
{
action();
}
void Func1()
{
}
void Func2()
{
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613055606im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
UI Button OnClick Function - How to get name of button that was clicked? 2 Answers
UI: Mouse events not working 1 Answer
Can't change UI Button Listeners 1 Answer
Any way to pass the function of a listener as a string? 1 Answer
onClick.AddListener() delegates don't appear on Inspector Events 1 Answer