Having trouble instantiating a UnityAction as a field rather than an anonymous delegate.

I need to be able to add and remove a listener by script. To do this I need to have the reference to the object I want to remove so an anonymous delegate won’t work.

I simply can’t figure out the syntax for the creation and storing in a field of a “UnityAction”.

E.G.

private UnityAction MyDel;

void Start()
{
      Button MyButton = this.transform.GetComponent<Button>();
      
      MyDel = //  ???????  How do I initialize this?

      MyButton.onClick.AddListener(MyDel);
}

private void MyUnityActionMethod()
{
      bool DoSomething = true;
}

Sorry, in case anyone comes across this, you just assign the method directly by name… I feel silly.

private UnityAction MyDel;

void Start()
{
      Button MyButton = this.transform.GetComponent<Button>();
     
      MyDel = MyUnityActionMethod;

      MyButton.onClick.AddListener(MyDel);
}

private void MyUnityActionMethod()
{
      bool DoSomething = true;
}
1 Like