user17773048
user17773048

Reputation:

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

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");
  }

Upvotes: 0

Views: 745

Answers (2)

John Wu
John Wu

Reputation: 52240

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()
);

Upvotes: 0

derHugo
derHugo

Reputation: 90639

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");
}

...

Upvotes: 1

Related Questions