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.

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

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
}

Rather than using Remove() or RemoveAll() static methods of Delegate class , you can use -= operator which has been overloaded for the same methods.