Function unsubscribe event immediately after being used

I’m searching for a way to make a function unsubscribe from the event right after it’s used.
I came up with the idea below of using anonymous function.

// This is not the actual code, just a simplication of what I wrote
public event Action unityAction;

Action subscribeFunction = null;
subscribeFunction = () =>
{
    Debug.Log("Function Called");
    // Do something
    unityAction -= subscribeFunction;
};

But it seems like it unsubscribes itself after being called twice like the picture below.
Any solutions? Thank you in advance.

I’ve attempted to answer but then, after rereading your post, I realized that I don’t understand what you’re trying to do at all.

Can you explain your setup in more detail? Like what part of your code is actually dispatching events, and what part is supposed to react on these events? Why do you need to self-unsubscribe and why are you using anonymous methods (which introduce closures) and so on.

I think there could be some misconceptions on your part and so any outright answer wouldn’t actually resolve your problem.

To be perfectly honest, I get a feel that you’re underestimating something of importance, and now that you’ve come up with a false solution, by helping you with that solution, it could be that we all waste time. Also known as an XY problem.

1 Like