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

Object reference not set to an instance of an object

Discussion in 'Scripting' started by Skeller, Feb 6, 2015.

  1. Skeller

    Skeller

    Joined:
    Feb 6, 2015
    Posts:
    3
    Hello guys, please help me. I have 3D game with player and cube. Cube is following me and i want to write script on meele attack but.....

    This is my code: PlayerAttack
    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. public class PlayerAttack : MonoBehaviour {
    6.  
    7.     public GameObject target;
    8.     // Use this for initialization
    9.     void Start () {
    10.    
    11.     }
    12.    
    13.     // Update is called once per frame
    14.     void Update () {
    15.    
    16.         if (Input.GetKey(KeyCode.F)){
    17.             Attack ();
    18.         }
    19.     }
    20.  
    21.     private void Attack(){
    22.         EnemyHealth eh = (EnemyHealth)target.GetComponent ("EnemyHealth");
    23.         eh.AddjustCurrentHealth (-10);
    24.     }
    25. }
    26.  

    My error is:
    NullReferenceException: Object reference not set to an instance of an object
    PlayerAttack.Update () (at Assets/Scripts/PlayerAttack.cs:17)
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,738
    Something doesn't look right there. NullReferenceExceptions generally mean that you're trying to dig into a reference that doesn't exist. If that error had happened on, say, line 22, it'd be easy - either target is null or it doesn't have an EnemyHealth component.

    However, there's nothing on or even near line 17 that could realistically trigger that exception. Is it possible the error is referring to an older version of that script or something like that? Make sure your script is saved and that it's compiling; clear your console; and run it again. Is it still exhibiting the same problem on the same line?
     
  3. Zaladur

    Zaladur

    Joined:
    Oct 20, 2012
    Posts:
    392
    I'm thinking he just didn't write the full stack trace. PlayerAttack.Update Line 17 is going to call Attack(), which will throw the exception in line 22 or 23, so it is reasonable to see it in the stack trace.

    You either don't have target set (Check the inspector) or your target gameObject does not have an EnemyHealth Component.

    edit - or the stack trace goes further and the Nullreference exception is happening inside of the enemy health class.
     
  4. Skeller

    Skeller

    Joined:
    Feb 6, 2015
    Posts:
    3
    I am idiot... I didnt have script "Enemy Health" as component on Cube... Little thing and much nerves :D Thank you :)