Assign UnityEvent by code? c#

This code allows you to assign in the inspector any method to MyEvent.

public UnityEvent MyEvent;

public void SomeMethod()
{
      MyEvent.Invoke();
}

Is it possible to assign a method by code instead of by inspector?

I’ve read many pages but haven’t found a simple answer.

You want to “AddListener”

MyEvent.AddListener(SomeMethod);

You would be using “MyEvent.Invoke()” to call “SomeMethod”

Docs:

An example of calling methods and assigning methods not using unity event.

using System;
    
    public Action method;
    float timer;
    float changeTime = 5.0f;
    bool toggle = false;
    
    void Start()
    {
        SetMethod(MethodA);
    }
    
    public void SetMethod(Action state)
    {
        method = state;
    }
    
    void Update()
    {
        method();
        timer += Time.deltaTime;
        if(timer > changeTime) {
            timer = 0.0f;
            if (!toggle)
            {
                SetMethod(MethodB);
            }
            else {
                SetMethod(MethodA);
            }
            toggle = !toggle;
        }
    }
    
    void MethodA()
    {
        Debug.Log("calling method A");
    }
    
    void MethodB()
    {
        Debug.Log("calling method B");
    }