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

The following code detects the difference between the player and the enemy. I’m getting this error:

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

Can someone please explain what I’m doing wrong? I’m new to Unity, so an in-depth explanation would be nice.

var player : Transform;

var distance = Vector3.Distance(player.transform.position, this.transform.position);
var attackDistance : float = 0.1;

function Update() {
	// If the player is in the enemy's distance
	if (distance <= attackDistance) {
		transform.LookAt(player);
		print("enemy about to attack");
	}
}

The null reference error is occurring because you are trying to use the player variable and it has nothing assigned to it.

Have you assigned anything to the player variable in the inspector? Look at where you attached the script and you will see a slot called player, you need to drag the GameObject that is the player into this slot.

Also your distance calculation should probably be in the Update function as it will only be calculated once in your code:

 var attackDistance : float = 0.1;
 
 function Update() {

 var distance = Vector3.Distance(player.transform.position, this.transform.position);

 // If the player is in the enemy's distance
 if (distance <= attackDistance) {
     transform.LookAt(player);
     print("enemy about to attack");
 }