NullReferenceException

I've got a function that checks for closest enemy and return it if within range:

target = FindClosestEnemy().transform;

But while it's out of range I get

NullReferenceException: Object reference not set to an instance of an object

This hogs the frames/sec as it keeps writing the error to the log file.

Thanks

As the error says, you're trying to refer to an object that doesn't exist. Check if it's null first before you do anything with it.

if(enemy != null)
{
   //Do what you want when their is an enemy.
}
else
{
   //Do what you want when their isn't an enemy.
}

Null essentially means "has not been assigned to anything". And you can't access any field or functions on something that is null, or you'll get an error and your script will exit.

In your case, `FindClosestEnemy()` is returning null when there are no enemies in range. So when you try to access the `transform` field, the script is failing.

If there is a possibility that something will return null, you need to include a null check before using it. In this case:

closestEnemy = FindClosestEnemy();
if (closestEnemy != null)
{
    // Put all code that depends on the enemy here.
    // Don't use closestEnemy outside this block.
    target = closestEnemy.transform;
    // More stuff.
}