0

My code looks like this:

public void ThrowAConfirmScreen(string msg, Action func)
{
    confirmField.SetActive(true);
    confirmText.text = msg;

    confirmButton.onClick.AddListener(() => {
        func();
        confirmField.SetActive(false);
    });

    cancelButton.onClick.AddListener(() => {
        confirmField.SetActive(false);
    });
}

I tried making confirmation window by following a Youtube tutorial and the confirmation window actually works, but if you press cancelButton for a few time before confirmButton the func action executes as many times as cancelButton was pressed before. For example if I pass the func action Debug.Log("aa"); after canceling confirm window (pressing cancelButton) for 4 times and then pressing confirm I would get this:

func repeated exactly 4 times

I can't figure out why this behavior occurs and what causes it, can you help me?

I've already tried passing action as arrow functions, as separately declared function, passing Func<> instead of Action.

2
  • 1
    It's not possible to tell from that code but I suspect that it's because you are calling ThrowAConfirmScreen multiple times. You are adding a listener to the onClick event of confirmButton each time you call that method so if you call it twice then you'll add two listeners, so clicking confirmButton once would cause func to be executed twice. Commented Dec 13, 2022 at 4:21
  • Oh, makes sense, I haven't thought of it. Thank you Commented Dec 13, 2022 at 4:40

1 Answer 1

3

This is because you are adding callbacks to the buttons each time that you called that function. You should remove the addlisteners from that method and create one method called SetupButtons for example and call that only one time.

The Action func() should be in a member variable then when you call the method ThrowAConfirmScreen set the value to the member variable. The method listener added in the confirm button should call the Action member variable.

    private Action callback;

    public void SetupCallback()
    {
        confirmButton.onClick.AddListener(() => {
            callback?.Invoke();
            confirmField.SetActive(false);
        });

        cancelButton.onClick.AddListener(() => {
            confirmField.SetActive(false);
        });
    }
    
    public void ThrowAConfirmScreen(string msg, Action func)
    {
        callback = func;
        confirmField.SetActive(true);
        confirmText.text = msg;

        
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.