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
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
}