Callback method to a destroyed object

Hey all

I make a server call in which upon receiving a response, I call my callback method. The problem is that in rare situations, this callback method might be in a gameobject that has been destroyed. This is resulting

MissingReferenceException: The object
of type ‘xyz’ has been
destroyed but you are still trying to
access it.

When I check if the callback is null, it is always returning false. Here is a sample code

  public class A : MonoBehaviour{
    
      private void initMethod(){
            B b_inst = new B();
            b.fetchResultsFromServer(myCallback);
     }
     private void myCallback(){

           Debug.Log("Success");
     }
}

public class B{
    Action callBack;
    public void fetchResultsFromServer(Action callBack){
           this.callBack =callBack;
           getResults();
     }
     private onResultReceived(){
          callBack();
    }

}

So how can I handle this situation when orginalCaller who has the callback method is null. Is there a way I can pull the object from the callback to check if it is destroyed?

Thank you

Make the myCallBack method take a parameter.

class A {
	private void initMethod(){
		B b_inst = new B();

		Action callbackAction = new Action(delegate {
			myCallback(this); //not sure if this is what you want to check but i guess you get the idea
		});

		b_inst.fetchResultsFromServer(callbackAction);
	}

	private void myCallback(A caller){
		if (caller == null) return;

		Debug.Log("Success");
	}
}

public class B{
	Action callBack;

	public void fetchResultsFromServer(Action callBack){
		this.callBack = callBack;
		getResults();
	}

	private void onResultReceived(){
		callBack();
	}

}

Hey I’m 4 years late but if your object is destroyed but you still have a refrence to it somewhere it won’t be seen as null if you do

if(destroyedObject == null)

instead do this

if(destroyedObject)