- Home /
How to remove a method from a delegate
I have added one method into a delegate, but i'm unable to remove it.
The code I'm using:
public delegate void MyDelegate();
static public MyDelegate delegateInstance;
void Start () {
delegateInstance = new MyDelegate(MyMethod);
delegateInstance -= new MyDelegate(MyMethod);
delegateInstance();
}
I suppose it would not run the MyMethod, because it was removed before I call the delegate. Yet it ignores my try to remove it.
Does $$anonymous$$y$$anonymous$$ethod happen to be JavaScript? Looks like there may be some issues with that: http://forum.unity3d.com/threads/30202-Removing-methods-C-delegates
Otherwise, your code works correctly for me.
Answer by Jeffom · Jan 28, 2013 at 06:41 PM
on your code you're not adding an event to be called by the delegate youre just setting the reference, that's why it won't work with the "-=" operator. try this(i'm not sure if it'll work):
public delegate void MyDelegate();
static public MyDelegate delegateInstance;
void Start () {
delegateInstance += new MyDelegate(MyMethod);
delegateInstance -= new MyDelegate(MyMethod);
delegateInstance();
}
to just remove the delegate reference set it to null and do a null check
delegateInstance = null
if( delegateInsatance != null )
delegateInstance();
for more info about events access http://msdn.microsoft.com/en-us/library/aa645739%28v=vs.71%29.aspx
Answer by MalikDrako · Jan 28, 2013 at 07:00 PM
You are trying to remove a different instance than you originally assigned, so it doesnt do anything. You dont need to create a new MyDelegate object when assigning, you can just give it a method that fits.
public delegate void MyDelegate();
static public MyDelegate delegateInstance;
void Start () {
delegateInstance += MyMethod; // using += allows it to call multiple methods
delegateInstance -= MyMethod;
if (delegateInstance != null) // you should null-check delegates
delegateInstance();
}
Using += will allow you to do something like this:
public delegate void MyDelegate();
static public MyDelegate delegateInstance;
void Start () {
delegateInstance += MyMethod;
delegateInstance += MyMethod2;
delegateInstance += MyMethod3;
delegateInstance -= MyMethod;
delegateInstance(); // will call MyMethod2 and MyMethod3 but not MyMethod
}
Answer by ammarhassan48 · Apr 04, 2017 at 09:52 AM
Rather than using Remove() or RemoveAll() static methods of Delegate class , you can use -= operator which has been overloaded for the same methods.