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 don't get it. you're explicitly setting ADic[7] to null and ask when it gets null?
I just want to know in what case "gameObject.name" inside of A::Func1 itself will throw NullReferenceException. Thanks for your reply.
some times because of error & probably A Aobj = ADic[7];
Answer by Fredex8 · Mar 01, 2016 at 06:30 AM
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
}
Answer by bob_feng_2000 · Mar 03, 2016 at 07:07 AM
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.