- Home /
Button onClick delegate with toggling method assignment
I am trying to create a UI Button which switches its onClick action between two different handlers whenever it is clicked.
Example: - Button handler: Open panel - Click - Panel opens. Handler changes to: Display message - Click - Message displays. Handler changes to: Open panel
Here is my demo code:
using UnityEngine;
using UnityEngine.UI;
public class ButtonWithTwoActions : MonoBehaviour
{
public Button button;
private delegate void ButtonAction();
private ButtonAction _buttonAction;
void OnEnable ()
{
_buttonAction += ActionOne;
button.onClick.AddListener( () => _buttonAction() );
}
void OnDisable ()
{
button.onClick.RemoveAllListeners();
}
void ActionOne()
{
// Perform action 1
_buttonAction -= ActionOne;
_buttonAction += ActionTwo;
}
void ActionTwo()
{
// Perform action 2
_buttonAction -= ActionTwo;
_buttonAction += ActionOne;
}
}
My problem: _buttonAction is called and calls Action 1. Action 1 needs to toggle the handler to a different method, but as soon as I do this, Action 2 gets called in the same frame, which I don't want. I only want it to be assigned to the delegate, so Action 2 gets called the next time I click my button.
Thanks for any suggestions! I'd also be happy to try different approaches as long as my button has two separate handlers which swap with every click.
just a suggestion I haven't tried. ins$$anonymous$$d of the delegate, why not AddListener/ RemoveListener on the button directly? AddListener ActionOne and within that Remove it and add Two.
or have just one action with
if (toggleAction = !toggleAction)
ActionOne();
else
ActionTwo();
where toggleAction is a bool