Search code examples
c#eventsevent-handlingaction

Subscribe to an Action event with a different return type method


I have an event:

public event Action OnDamageTaken;

I'd like to subscribe to it in my behavior tree, but with a return type of TaskStatus, which when evaluated to TaskStatus.Success, would end current Task execution in the tree, like so:

Vegetation.OnDestroy += VegetationDestroyed;

public TaskStatus VegetationDestroyed()
{
    Owner.FindTask<JobChooser>().CurrentJob.OnJobCompleted();
    return TaskStatus.Success;
}

However, I get the following error:

error

Is something like this possible to do, and if not, why? I thought since the Action event passes no arguments, therefore, we can subscribe with a method that has any return type, as long as that method too requires no parameters.


Solution

  • You can wrap the method inside a lambda:

    Vegetation.OnDestroy += () => VegetationDestroyed();
    

    If you want to unsubscribe again from the event, you have to store the lambda inside a variable:

    Action onDestroy = () => VegetationDestroyed();
    Vegetation.OnDestroy += onDestroy;
    Vegetation.OnDestroy -= onDestroy;
    

    Online demo: https://dotnetfiddle.net/AOYqbf