Search Unity

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

Discussion in 'Scripting' started by UnstoppableAwesomeness, Oct 30, 2020.

  1. UnstoppableAwesomeness

    UnstoppableAwesomeness

    Joined:
    Oct 26, 2020
    Posts:
    33
    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:
    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.AI;
    3. public class EnemyController : MonoBehaviour
    4.  
    5. {
    6.     public float lookRadius = 10f;
    7.  
    8.     private float zombieHealth;
    9.  
    10.     public Animator zombieAnimation;
    11.  
    12.     public GameObject firstPerson;
    13.  
    14.    
    15.    
    16.  
    17.     public int damage = -20;
    18.     private PlayerHealth firstPersonInfo;
    19.     private int playerHealth;
    20.  
    21.     Transform target;
    22.     NavMeshAgent agent;
    23.  
    24.  
    25.  
    26.     // Start is called before the first frame update
    27.     void Start()
    28.     {
    29.         target = PlayerManager.instance.player.transform;
    30.         agent = GetComponent<NavMeshAgent>();
    31.         firstPersonInfo = firstPerson.GetComponent<PlayerHealth>();
    32.         playerHealth = firstPersonInfo.health;
    33.        
    34.     }
    35.  
    36.     // Update is called once per frame
    37.     void Update()
    38.     {
    39.         zombieHealth = GetComponent<Target>().health;
    40.         float distance = Vector3.Distance(target.position, transform.position);
    41.  
    42.         if (distance <= lookRadius && zombieHealth > 0)
    43.         {
    44.             agent.SetDestination(target.position);
    45.             zombieAnimation.SetBool("walking", true);
    46.             zombieAnimation.SetBool("attacking", false);
    47.  
    48.             if (distance <= agent.stoppingDistance + .3)
    49.             {
    50.                
    51.                 zombieAnimation.SetBool("attacking", true);
    52.                 FaceTarget();
    53.                // Attack();
    54.              
    55.             }
    56.            
    57.  
    58.         }
    59.  
    60.     }
    61.  
    62.     void FaceTarget()
    63.     {
    64.         Vector3 directon = (target.position - transform.position).normalized;
    65.         Quaternion lookRotation = Quaternion.LookRotation(new Vector3(directon.x, 0, directon.z));
    66.         transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime * 5f);
    67.     }
    68.  
    69.     /*void Attack()
    70.     {
    71.         playerHealth -= damage;
    72.         Debug.Log(playerHealth);
    73.     }*/
    74.  
    75.     void OnDrawGizmosSelected()
    76.     {
    77.         Gizmos.color = Color.red;
    78.         Gizmos.DrawWireSphere(transform.position, lookRadius);
    79.     }
    80. }
    Here is my Player Health Script (this is sitting on my player, not my enemy):
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class PlayerHealth : MonoBehaviour
    6. {
    7.     public int health = 100;
    8. }
    Thanks in advance for any help!
     
  2. Terraya

    Terraya

    Joined:
    Mar 8, 2018
    Posts:
    646
    It cant find the Component on your GameObject:

    Code (CSharp):
    1. public GameObject firstPerson;
    have you assigned it in the inspector?
     
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,686
    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:

    https://forum.unity.com/threads/why-do-my-music-ignore-the-sliders.993849/#post-6453695

    Step by step, break it down, find the problem.
     
    Terraya likes this.
  4. UnstoppableAwesomeness

    UnstoppableAwesomeness

    Joined:
    Oct 26, 2020
    Posts:
    33
    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.
     
  5. UnstoppableAwesomeness

    UnstoppableAwesomeness

    Joined:
    Oct 26, 2020
    Posts:
    33
    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.
     
  6. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,686
    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.
     
  7. raarc

    raarc

    Joined:
    Jun 15, 2020
    Posts:
    535
    do you have firstPerson; assigned in the inspector
     
  8. UnstoppableAwesomeness

    UnstoppableAwesomeness

    Joined:
    Oct 26, 2020
    Posts:
    33
    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?
     
  9. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,686
    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.
     
  10. UnstoppableAwesomeness

    UnstoppableAwesomeness

    Joined:
    Oct 26, 2020
    Posts:
    33
    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.
     
  11. UnstoppableAwesomeness

    UnstoppableAwesomeness

    Joined:
    Oct 26, 2020
    Posts:
    33
    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!
     
    Kurt-Dekker likes this.
  12. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,686
    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!