Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

NullReferenceException: Object Reference not set to an Instance of an Object?

Discussion in 'Editor & General Support' started by yeezusbetch, Oct 19, 2014.

  1. yeezusbetch

    yeezusbetch

    Joined:
    Oct 19, 2014
    Posts:
    1
    So I'm doing the Nightmare tutorial on the Unity Website, and I've gotten to the point where I'm setting up the player's health, and now having a way for the enemies to attack. I have the exact same thing (as far as I can tell) as the people in the video, and I even copy and pasted the code right from the website, yet it persists on telling me this error: NullReferenceException: Object Reference not set to an Instance of an Object
    EnemyAttack.Update () (at Assets/Scripts/Enemy/EnemyAttack.cs:64)

    This is my EnemyAttack script:

    Code (CSharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5.  
    6. public class EnemyAttack : MonoBehaviour
    7. {
    8.     public float timeBetweenAttacks = 0.5f;     // The time in seconds between each attack.
    9.     public int attackDamage = 10;               // The amount of health taken away per attack.
    10.    
    11.    
    12.     Animator anim;                              // Reference to the animator component.
    13.     GameObject player;                          // Reference to the player GameObject.
    14.     PlayerHealth playerHealth;                  // Reference to the player's health.
    15.     EnemyHealth enemyHealth;                    // Reference to this enemy's health.
    16.     bool playerInRange;                         // Whether player is within the trigger collider and can be attacked.
    17.     float timer;                                // Timer for counting up to the next attack.
    18.    
    19.    
    20.     void Awake ()
    21.     {
    22.         // Setting up the references.
    23.         player = GameObject.FindGameObjectWithTag ("Player");
    24.         playerHealth = player.GetComponent <PlayerHealth> ();
    25.         enemyHealth = GetComponent<EnemyHealth>();
    26.         anim = GetComponent <Animator> ();
    27.     }
    28.    
    29.    
    30.     void OnTriggerEnter (Collider other)
    31.     {
    32.         // If the entering collider is the player...
    33.         if(other.gameObject == player)
    34.         {
    35.             // ... the player is in range.
    36.             playerInRange = true;
    37.         }
    38.     }
    39.    
    40.    
    41.     void OnTriggerExit (Collider other)
    42.     {
    43.         // If the exiting collider is the player...
    44.         if(other.gameObject == player)
    45.         {
    46.             // ... the player is no longer in range.
    47.             playerInRange = false;
    48.         }
    49.     }
    50.    
    51.    
    52.     void Update ()
    53.     {
    54.         // Add the time since Update was last called to the timer.
    55.         timer += Time.deltaTime;
    56.        
    57.         // If the timer exceeds the time between attacks, the player is in range and this enemy is alive...
    58.         if(timer >= timeBetweenAttacks && playerInRange && enemyHealth.currentHealth > 0)
    59.         {
    60.             // ... attack.
    61.             Attack ();
    62.         }
    63.        
    64.         // If the player has zero or less health...
    65.         if(playerHealth.currentHealth <= 0)
    66.         {
    67.             // ... tell the animator the player is dead.
    68.             anim.SetTrigger ("PlayerDead");
    69.         }
    70.     }
    71.    
    72.    
    73.     void Attack ()
    74.     {
    75.         // Reset the timer.
    76.         timer = 0f;
    77.        
    78.         // If the player has health to lose...
    79.         if(playerHealth.currentHealth > 0)
    80.         {
    81.             // ... damage the player.
    82.             playerHealth.TakeDamage (attackDamage);
    83.         }
    84.     }
    85. }
    And this is my PlayerHealth script, if it might help:

    Code (CSharp):
    1.  
    2. using UnityEngine;
    3. using UnityEngine.UI;
    4. using System.Collections;
    5.  
    6. public class PlayerHealth : MonoBehaviour
    7. {
    8.     public int startingHealth = 100;
    9.     public int currentHealth;
    10.     public Slider healthSlider;
    11.     public Image damageImage;
    12.     public AudioClip deathClip;
    13.     public float flashSpeed = 5f;
    14.     public Color flashColour = new Color(1f, 0f, 0f, 0.1f);
    15.  
    16.  
    17.     Animator anim;
    18.     AudioSource playerAudio;
    19.     PlayerMovement playerMovement;
    20.     //PlayerShooting playerShooting;
    21.     bool isDead;
    22.     bool damaged;
    23.  
    24.  
    25.     void Awake ()
    26.     {
    27.         anim = GetComponent <Animator> ();
    28.         playerAudio = GetComponent <AudioSource> ();
    29.         playerMovement = GetComponent <PlayerMovement> ();
    30.         //playerShooting = GetComponentInChildren <PlayerShooting> ();
    31.         currentHealth = startingHealth;
    32.     }
    33.  
    34.  
    35.     void Update ()
    36.     {
    37.         if(damaged)
    38.         {
    39.             damageImage.color = flashColour;
    40.         }
    41.         else
    42.         {
    43.             damageImage.color = Color.Lerp (damageImage.color, Color.clear, flashSpeed * Time.deltaTime);
    44.         }
    45.         damaged = false;
    46.     }
    47.  
    48.  
    49.     public void TakeDamage (int amount)
    50.     {
    51.         damaged = true;
    52.  
    53.         currentHealth -= amount;
    54.  
    55.         healthSlider.value = currentHealth;
    56.  
    57.         playerAudio.Play ();
    58.  
    59.         if(currentHealth <= 0 && !isDead)
    60.         {
    61.             Death ();
    62.         }
    63.     }
    64.  
    65.  
    66.     void Death ()
    67.     {
    68.         isDead = true;
    69.  
    70.         //playerShooting.DisableEffects ();
    71.  
    72.         anim.SetTrigger ("Die");
    73.  
    74.         playerAudio.clip = deathClip;
    75.         playerAudio.Play ();
    76.  
    77.         playerMovement.enabled = false;
    78.         //playerShooting.enabled = false;
    79.     }
    80. }
    81.  
    I am extremely new to this, so please take it easy on me. I greatly appreciate all input. Thank you :)
     
  2. crzyman

    crzyman

    Joined:
    Oct 24, 2014
    Posts:
    5
    Anyone? I have the exact same issue?
     
  3. Graham-Dunnett

    Graham-Dunnett

    Unity Technologies

    Joined:
    Jun 2, 2009
    Posts:
    4,287
    Line 64 is line 65 in your forum post. It is accessing the currentHealth property on the playerHealth object. The NRE basically means that playerHealth hasn't been set up. That's looked up on line 24, by getting the component (script) of type PlayerHealth from the player. In turn, the player variable is looked up by looking for a game object tagged with "Player". My guess is that there is such a tagged object, but it does not have a PlayerHealth script attached to it.
     
  4. crzyman

    crzyman

    Joined:
    Oct 24, 2014
    Posts:
    5
    I appreciate your response. I have the PlayerHealth script attached to the game object "Player" with the tag "Player". For some reason The Enemy Attack script that is attached to the game object, "Zombunny", isn't pulling the value of playerHealth from the PlayerHealth script. Any other possibilities?
     
  5. drewradley

    drewradley

    Joined:
    Sep 22, 2010
    Posts:
    3,063
    Is the player spawned into the scene and the zombunny already there? If the player spawns, you can't get a reference to it in awake of objects already in the scene. Put "if(!player)player = GameObject.FindGameObjectWithTag ("Player");" as the first line of the attack function of the zombunny.
     
  6. crzyman

    crzyman

    Joined:
    Oct 24, 2014
    Posts:
    5
    Thanks for the reply. I tried your suggestion, but I'm still getting the same error. Maybe it has to do with the fact that this is Unity 4.6 beta?
     
  7. Graham-Dunnett

    Graham-Dunnett

    Unity Technologies

    Joined:
    Jun 2, 2009
    Posts:
    4,287
    Try renaming Awake() as Start(). I'm not a big fan of Awake, specifically when you try and access other game objects. It's possible that the Awake gets called before other game objects are even created.
     
  8. crzyman

    crzyman

    Joined:
    Oct 24, 2014
    Posts:
    5
    I renamed Awake() as Start() in all the scripts that are being used in the scene, but still getting the same error. I went back and followed the tutorial step by step using a new project and scene only to be faced with the same error. On to something else I guess. Not a total loss as I did learn a few things along the way. Thank you for your help.
     
  9. Carpe-Denius

    Carpe-Denius

    Joined:
    May 17, 2013
    Posts:
    842
    Put the following at the end of your Start() method:

    Debug.Log(player);
    Debug.Log(playerHealth);

    Ideally, the console window should say "SomeGameObject (GameObject)" and in a new line "SomeOtherObject (PlayerHealth)"
    if one or both say "null", you are not getting the right object. If the first is your player gameobject and the second one "null", then your player doesn't have a playerhealth-script
     
  10. crzyman

    crzyman

    Joined:
    Oct 24, 2014
    Posts:
    5
    Thank you so much. The first was my player game object and the second one was "null". The PlayerHealth script was attached to the Player game object, but the child object (mesh) was tagged as Player, causing the script to reference the game object's child. I really appreciate the help.
     
  11. falcon0172

    falcon0172

    Joined:
    Jan 29, 2015
    Posts:
    3
    buddy I am still getting the error. What should I do?
     
  12. maeeeexx

    maeeeexx

    Joined:
    Feb 14, 2015
    Posts:
    1
    Comment #10 by crzyman helped me, had the same issue, thanks bro!
     
  13. BarneytheDinoDuck

    BarneytheDinoDuck

    Joined:
    Jul 17, 2015
    Posts:
    7
    Same error for me but what is happening is that when i shoot and kill the zombunny he doesnt do his death animation and he doesn't vanish he just keeps following me around and when he gets to me he just stands there. I am a beginner at unity so as the other guy said take it easy on me
     
  14. BarneytheDinoDuck

    BarneytheDinoDuck

    Joined:
    Jul 17, 2015
    Posts:
    7
    i just tested it and when i kill him he still hurts me
     
  15. unity_tR2VYjdiZS8K9A

    unity_tR2VYjdiZS8K9A

    Joined:
    Jan 29, 2018
    Posts:
    2
    I have the same problem and both saying null what i can i do :3
    please help me :(
     
  16. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    Null Reference errors are all debugged in the same way. Look in the console for the first instance of a null reference error. Go to the line of code it points to, and look at what possible variables could be null that you are trying to use. Then add debugging to figure out which one is null, which is often just checking them with Debug.Log. After you figure out which one is null, you then figure out how to make it not null before trying to use it.

    The process is exactly the same every time you encounter this error.
     
    Carpe-Denius likes this.