- Home /
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
Answer by JedBeryll · Aug 19, 2016 at 06:40 AM
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();
}
}
Thank you. I was hoping I can check if it is null when I am at B. Because the moment you you call the callBack, you are in a null space (in which I can check if (this == null) and no need for parameter. So I wanted to know it is null when I am inside onResultReceived. I will accept it for now since no other answer and this is a valid one :)
Answer by jfonz001 · Sep 05, 2020 at 07:12 PM
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)
Your answer
![](https://koobas.hobune.stream/wayback/20220612091119im_/https://answers.unity.com/themes/thub/images/avi.jpg)