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

Hello. I am working on a FPS game, and I am working on making the enemy do damge to the player. I am going about this by using the GetComponet<>() function, and setting the component equal to a private variable. However, everytime I do this, I receive a Null Reference error. One thing to point out is that the variable I am trying to reference is not sitting on the same game object as my script (I’ll explain more when I post the code).

Here is the full error:
NullReferenceException: Object reference not set to an instance of an object
EnemyController.Start () (at Assets/Scripts/EnemyController.cs:32)

Here is my Enemy Controller Script:

using UnityEngine;
using UnityEngine.AI;
public class EnemyController : MonoBehaviour

{
    public float lookRadius = 10f;

    private float zombieHealth;

    public Animator zombieAnimation;

    public GameObject firstPerson;

   
    

    public int damage = -20;
    private PlayerHealth firstPersonInfo;
    private int playerHealth;

    Transform target;
    NavMeshAgent agent;



    // Start is called before the first frame update
    void Start()
    {
        target = PlayerManager.instance.player.transform;
        agent = GetComponent<NavMeshAgent>();
        firstPersonInfo = firstPerson.GetComponent<PlayerHealth>();
        playerHealth = firstPersonInfo.health;
       
    }

    // Update is called once per frame
    void Update()
    {
        zombieHealth = GetComponent<Target>().health;
        float distance = Vector3.Distance(target.position, transform.position);

        if (distance <= lookRadius && zombieHealth > 0)
        {
            agent.SetDestination(target.position);
            zombieAnimation.SetBool("walking", true);
            zombieAnimation.SetBool("attacking", false);

            if (distance <= agent.stoppingDistance + .3)
            {
               
                zombieAnimation.SetBool("attacking", true);
                FaceTarget();
               // Attack();
              
            }
           

        }

    }

    void FaceTarget()
    {
        Vector3 directon = (target.position - transform.position).normalized;
        Quaternion lookRotation = Quaternion.LookRotation(new Vector3(directon.x, 0, directon.z));
        transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime * 5f);
    }

    /*void Attack()
    {
        playerHealth -= damage;
        Debug.Log(playerHealth);
    }*/

    void OnDrawGizmosSelected()
    {
        Gizmos.color = Color.red;
        Gizmos.DrawWireSphere(transform.position, lookRadius);
    }
}

Here is my Player Health Script (this is sitting on my player, not my enemy):

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerHealth : MonoBehaviour
{
    public int health = 100;
}

Thanks in advance for any help!

It cant find the Component on your GameObject:

public GameObject firstPerson;

have you assigned it in the inspector?

Some notes on how to fix a NullReferenceException error in Unity3D

  • also known as: Unassigned Reference Exception
  • also known as: Missing Reference Exception

http://plbm.com/?p=221

The basic steps outlined above are:

  • Identify what is null
  • Identify why it is null
  • Fix that.

Expect to see this error a LOT. It’s easily the most common thing to do when working. Learn how to fix it rapidly. It’s easy. See the above link for more tips.

This is the kind of mindset and thinking process you need to bring to this problem:

Step by step, break it down, find the problem.

1 Like

Alright. I’ve figured out that I only get this error whenever I try to reference a variable inside of the script. The variable I’m calling is there, however I’m not doing anything with it yet. The script I am referencing is on an object, but on the script, I’m refrencing the prefab, not the object already in the game. So maybe I need to instantiate my player at the beginning of the game. Let me try these things that I’ve listed an I will reply to you.

Never mind, that didn’t fix my problem… I’ve thought through what you have said, and I cannot find how it would be void. I’m still looking through it, but if you could give me a hint, that would be great.

What variable is null? Try putting a Debug.Log( "Setting!") line where the variable is supposed to be set, and a Debug.Log( "Using!"); line where it is used, make sure the first gets called before the second.

do you have firstPerson; assigned in the inspector

I have not used the variable anywhere yet. All I am doing is setting the variable equal to the value of a variable in a different script. Could I be getting this error becuase I am not using it? Just setting it?

Yes, yes you have. You are trying to use it and it is failing because it is null. Otherwise you would not have the error.

Anywhere you have blahblahblah.foofoofoo and you get a nullreference, this means blahblahblah has not been set.

Go back and review the basic steps in the first post I replied.

Ohhh. I think I know what the problem is now. Let me go back and follow the steps you sent me, and I’ll keep you updated.

I found my issue, and was able to fix it. The entire time, I thought a different variable was void. The troubleshooting you said to do really helped. Thank you a lot!

1 Like

This is an easy trap to fall into… it has bitten me many times. The only sure defense is to attach the debugger and look at the variable you think is null, and say “Yep, it’s null right before I hit the problem point.”

Glad you’re operating again!