Boolean null reference exception

Hi everyone,

I have a boolean that checks wether an enemy is in sight and if so the unit will stop moving. When I execute the script however I get a null reference exception saying; “object reference not set as an instance of this object**”**
error line is in script2; if(gameObject.GetComponent().FindPath){

Below are the two scripts thats are communicating trough the boolean FindPath.

// script Turret

public bool FindPath = true;


  if(nearestEnemy==null)
{
FindPath=true;
}
else{
nearestEnemy.GetComponent<Renderer>().material.color=Color.blue;
FindPath=false;
}

// script Move

  voidLateUpdate(){
if(gameObject.GetComponent<Turret>().FindPath){  //this is the error line null reference exception
transform.GetComponent<NavMeshAgent>().destination=Destionationpoint.position;
}
}

Any help would be much apreciated

Either gameObject is null or GetComponent() returns null because there’s no OverlapSphere component attached to the gameObject.

1 Like

I dont think it is a null reference exception on the boolean, but more on the GetComponent. Perhaps for some reason it didnt find it. You should always try to include the check to see if the GetComponent returned null. If so, the rest of that should be avoided.

Please use code tags.

As the others have said, this is happening because there’s no OverlapSphere component attached to your gameObject.

If the script you posted needs an OverlapSphere, you could use the RequireComponent tag to make sure that it’s always added when it’s needed. Or, you could add it to the gameobject on Awake:

void Awake() {
    gameObject.AddComponent<OverlapSphere>();
}

Thanks for the replies. To avoid misunderstandings my script is named OverlapSphere. Thats whats it’s referring too not the actual OverlapSphere.

EDIT; Overlapsphere script is renamed to Turret to avoid misunderstandings regarding to the actual OverlapSphere.

If you haven’t redeclared gameObject field inside Move script, then it still references the game object that this Move script is attached to.

When you execute gameObject.GetComponent(), the function returns a reference to the OverlapSphere component that is attached to this game object. If there’s no OverlapSphere component attached to this game object, GetComponent returns a null reference. And if it does return a null reference, then reading or writing its FindPath field will generate NullReferenceException.

I renamed my OverlapSphere script to Turret script. But I still get the same error.

 if(gameObject.GetComponent<Turret>().FindPath){

The turret script is attached to the object so it should find it.

Turret component is attached to the same object that Move component is, isn’t it?

No it wasn’t…it finally works ! Was working on this issue all day I can’t believe I oversaw that.

Thank you and everyone replying.

Cheers