Home > Mobile >  is it possible to have two on click events in one button then execute one before the other
is it possible to have two on click events in one button then execute one before the other

Time:01-14

good day I am trying to have two onclick events on one button. then execute one before the other I use the code below, but it executes at the same time.

  void Start() {
      someUIButtonReference.onClick.AddListener(SomeFunction1); // first
      someUIButtonReference.onClick.AddListener(SomeFunction2); // second
  }
  void SomeFunction1() {
      Debug.Log("SomeFunction1");
  }
  void SomeFunction2() {
      Debug.Log("SomeFunction2");
  }

CodePudding user response:

It sounds to me what you actually want is alternate between the callbacks and each click only execute one of them.

If you have only two of them you could simply use a bool flag and do

private bool isSecondClick;

void Start() 
{
    // Use a wrapper callback instead
  someUIButtonReference.onClick.AddListener(HandleClick);
}

private void HandleClick()
{
    if(!isSecondClick)
    {
        SomeFunction1();
    }
    else
    {
        SomeFunction2();
    }

    isSecondClick = !isSecondClick;
}

void SomeFunction1()
{
    Debug.Log("SomeFunction1");
}

void SomeFunction2() 
{
    Debug.Log("SomeFunction2");
}

If there are going to be more callbacks then you could rather use something like e.g.

private int index;

private Action[] listeners = new Action[]
{
    SomeFunction1,
    SomeFunction2,
    SomeFunction3,
    ...
};

void Start() 
{
    // Use a wrapper callback instead
  someUIButtonReference.onClick.AddListener(HandleClick);
}

private void HandleClick()
{
    var action = listeners[index];

    action.Invoke();

    index = (index   1) % listeners.Length;
}

void SomeFunction1()
{
    Debug.Log("SomeFunction1");
}

void SomeFunction2() 
{
    Debug.Log("SomeFunction2");
}

void SomeFunction3() 
{
    Debug.Log("SomeFunction3");
}

...

CodePudding user response:

You could define a flag and use it in a lambda expression to alternate between the functions. The flag will be closured.

bool flag = false;
someUIButtonReference.onClick.AddListener
(
    () => flag = !flag ? SomeFunction1() : SomeFunction2()
);
  •  Tags:  
  • Related