Home > Mobile >  Passing an function as parameters in Unity C#
Passing an function as parameters in Unity C#

Time:12-13

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.

CodePudding user response:

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;

        
    }
  • Related