'Multi Class Unity Action Events

A quick question on unity action stuffs. I know I could do something like this in unity:

public class Test: MonoBehaviour{
    public event UnityAction Action;
    public void Start()
    {
        Action += [Method Name Here];
    }
}

However I was wondering if I could create a method to encapsulate the action across different classes like this:

public class Test: MonoBehaviour{
    public event UnityAction Action;
    public void Start()
    {
        Action += [Method Name Here];
    }

    public void AddAction(method)
    {
        Action += method;
    }
}

//in a different script
public class Test2: MonoBehaviour
{
    private Test test;
    
    public void TestAction()
    {

    }    

    test.AddAction(TestAction);
}

Is it possible to call the method like the way I showed above, or is it necessary to call the Action variable directly from the Test class?

Any advice given are all appreciated!



Solution 1:[1]

First of all there basically isn't really a difference between UnityAction and the normal System.Action.

Both are just delegates for a parameter-less void method. So if you use them for an event I would actually rather simply stick to

public event Action XY;

but that's probably a matter of taste and use case.


And then of course you can if you mean e.g. this

public class Test: MonoBehaviour
{
    public event /*Unity*/Action onAction;

    public void AddAction(/*Unity*/Action action)
    {
        onAction += action;
    }

    public void InvokeOnAction()
    {
        onAction?.Invoke();
    }
}

and

public class Test2: MonoBehaviour
{
    private Test test;
    
    private void Start()
    {
        test.AddAction(TestAction);

        test.InvokeOnAction();
    }

    public void TestAction()
    {
        Debug.Log(nameof(TestAction));
    }   
}

However, if your event is public anyway then nothing prevents you from actually simply doing rather

private void Start()
{
    test.onAction += TestAction;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 derHugo