- Home /
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");
}
}
Answer by karljj1 · Apr 26, 2015 at 09:55 PM
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");
}
I do have the player assigned to the variable in the inspector, and I was still getting an error until I put the distance variables inside the update function. Thanks :)
Your answer
![](https://koobas.hobune.stream/wayback/20220613194107im_/https://answers.unity.com/themes/thub/images/avi.jpg)