- Home /
Duplicate Question
NullReference Exception when checking for Null
I am getting an NullReference Exception when I am trying to check if a GameObject is null.
public GameObject target;
[...]
if (target != null ) doSomething();
I know that target can be null, so I am checking for null, but this check throws a NullReference Exception....
Any ideas why this is happening?
Are you certain it's the check, and not the call to "doSomething()"?
Yes. If I write the code like this
if (target != null)
doSomething;
the error is thrown on the first line.
Also I tried an empty doSomething() method - did not help.
problem is somewhere else, so can you tell me whole error you got?
NPCBehaviour.FixedUpdate () (at Assets/AI/NPCBehaviour.cs:86) void FixedUpdate () {NullReferenceException: Object reference not set to an instance of an object
if (target==null && persuer==null) searchForEnemy();
if (target!=null && //line 86 target.GetComponent().persuer!=null){ checkIfEnemyGotAway(); } if (target!=null) shoot(); calcSearchVector(); calcPersueVector(); calcEvadeVector(); calcObstacleVector(); calcTetherVector(); calcFinalVector(); Vector3 _direction = (finalVector - transform.position).normalized; Quaternion _lookRotation = Quaternion.LookRotation(_direction); transform.rotation =Quaternion.Slerp(transform.rotation, _lookRotation, Time.deltaTime * rotationSpeed); }
Answer by Hoeloe · Sep 23, 2013 at 09:09 AM
Even with a line break, the whole if statement is considered one line. The error is that the GetComponent call is returning null.