In what situation Component.gameObject method throws NullReferenceException?

Have anybody ever met the same problem with me? When I call Component.gameObject function it throws “NullReferenceException: Object reference not set to an instance of an object” rather than “MissReferenceException: xxx”.

class A: MonoBehaviour{
public void Func1()
{
Debug.Log(gameObject.name);//throw NullReferenceException here because of gameObject invoke not .name
}
}


class B:MonoBehaviour{
public static Dictionary<int, A> ADic = new Dictionary<int, A>();
public static A AGOInScene;//initialized in somewhere and refers to a //GameObject in current scene.

public void Start()
{
AGOInScene = xxxx;//initialized hereand refers to a //GameObject in current scene.
ADic[7] = AGOInScene;
}

public void DestroyInDifferentWaysBeforeCallAFunc1()
{
case 1: ADic[7] = null;//this will lead to "Aobj.Func1();" throwing NullReferenceException
case 2: DestroyImmediate(ADic[7]);//Nothing will happen in Aobj.Func1() but it will throw MissReferenceException inside A::Func1()

So in what case will cause NullReferenceException inside A::Func1()?
}

public void CallAFunc1()
{
A Aobj = ADic[7];
Aobj.Func1();
}

}

So in what case will cause NullReferenceException inside A::Func1()?
Thanks in advance.

I’m really not entirely sure what you’re actually trying to do with this as I can’t follow your script very well but it looks like you’re trying to do something excessively complicated to handle null references when something simple would do the job:

if (AGOInScene!= null)
{
     //Do something
}

Thank you Fred. I found even “AGOInScene” is null because of DestroyImmediate(AGOInScene) in Coroutine, it still can went into the block //Do something. in your code except you set AGOInScene=null explicitly.