title: How to best avoid memoryleaks when using UnityActions or C# Actions
body: <p>Ok, I am working with public static UnityActions for event driven multi delegate execution and I want to avoid memory leaks. I am worried that I miss removing a registered delegate. So I came up with the following construct:
  Immediately when registering for an event I also register the command for unregistering to a separate action that I can execute at the end of the program like so:</p>
  <pre><code>// first establish a delegate to collect everything we need to de-register later OnDestroy
  private delegate void Dreg();
  private Dreg dreg;
  
  // register for the event and create an entry in the de-register list 
  //for later execution:
              MyEvents.SomeEvent += HandleSomeEvent;
              dreg += () =&gt; { MyEvents.SomeEvent -= HandleSomeEvent; };
  </code></pre>
  <p>At the end of the application I just need to invoke &quot;dreg&quot; to clear all registrations. This si working fine so far.</p>
  <p>My question is: Can I wrap these two statements more elegantly into a function so that I just have to issue one statement instead of two? I have tried but I fail in the assignments.
  My experiment looked something like this:</p>
  <pre><code>public static void RegisterForEvent(UnityAction _eventToRegisterFor, UnityAction _thingToAdd)
  {
      _eventToRegisterFor += _thingToAdd;
      dreg += () =&gt; _eventToRegisterFor -= _delegateToAdd;
  }
  ...
  ...Register(MyEvents.SomeEvent,HandleSomeEvent);// using this to register
  
  ...
  ...dreg.invoke;//near the end of the application to de-register everything
  </code></pre>
  <p>This does not seem to be possible.
  My problem seems to be that I don't quite understand, what type &quot;thingToAdd&quot; actually is that I am assigning to MyEvents.SomeEvent? Is that a delegate? Is it a string that is resolved at runtime? is it a function??
  I tried to work with C# Actions as well but did not succeed with that either.
  Any suggestions will be much appreciated! Many thx before hand :-)</p>