Search Unity

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

Discussion in 'Scripting' started by kivakabuto, Oct 13, 2014.

Thread Status:
Not open for further replies.
  1. kivakabuto

    kivakabuto

    Joined:
    Oct 13, 2014
    Posts:
    2
    guys..i wanna ask something... iam still newbie in game development so i took a tutorial pack on asset store name nightmare the game hnity training day 2014. iam still learn from here. so the question is when i want to test the game there is a notice about (NullReferenceException: Object reference not set to an instance of an object) EnemyMovement.Update () (at Assets/Scripts/Enemy/EnemyMovement.cs:23)

    and the script :

    using UnityEngine;
    using System.Collections;

    public class EnemyMovement : MonoBehaviour
    {
    Transform player;
    PlayerHealth playerHealth;
    EnemyHealth enemyHealth;
    NavMeshAgent nav;


    void Awake ()
    {
    player = GameObject.FindGameObjectWithTag ("Player").transform;
    playerHealth = player.GetComponent <PlayerHealth> ();
    enemyHealth = GetComponent <EnemyHealth> ();
    nav = GetComponent <NavMeshAgent> ();
    }


    void Update ()
    {
    if(enemyHealth.currentHealth > 0 && playerHealth.currentHealth > 0)
    {
    nav.SetDestination (player.position);
    }
    else
    {
    nav.enabled = false;
    }
    }
    }


    i tried to be exactly same with the tutorial but this thing happens...
    can anyone tell me what is goes wrong..

    //sorry for my bad english
     
    Xenfor, kellylin482 and danthecoolman like this.
  2. Pirs01

    Pirs01

    Joined:
    Sep 30, 2012
    Posts:
    389
    Tom980 likes this.
  3. THoeppner

    THoeppner

    Joined:
    Oct 10, 2012
    Posts:
    205
    I'm thining you forgot either to attach the PlayerHealth component to the Player GameObject or the EnemyHealth component to your enemy GameObject.

    It is good practice to check if the GetComponent method delivers a valid value. And if not to write a Debug method. Than it's easier so solve such problems.

    Code (CSharp):
    1. enemyHealth = GetComponent <EnemyHealth>();
    2. if (enemyHealth == null)
    3. {
    4.     Debug.LogError("No EnemyHealth component found.");  
    5. }
    6.  
     
  4. dean-o

    dean-o

    Joined:
    Oct 13, 2014
    Posts:
    7
    I'm getting the same issue. Very frustrating after spending a day carefully following the steps! Never mind, that's game making I suppose! Anyway, it happens when the Zombunny & Zombears are first instantiated, a couple of seconds after the game is run. Hope this helps us get somewhere!
     
    Orangepolarbear23 likes this.
  5. dean-o

    dean-o

    Joined:
    Oct 13, 2014
    Posts:
    7
    This doesn't seem to be the case as both objects (which are prefabs) have the relevant scripts attached.
     
  6. Pirs01

    Pirs01

    Joined:
    Sep 30, 2012
    Posts:
    389
    We can keep speculating about some stuff you guys did on your comuters that no one knows anything about OR you can post the code where the error occurs and say where exactly does it occur and what the error is exactly so we can tell wht's wrong exactly and how to fix it exactly as requested before.
     
  7. dean-o

    dean-o

    Joined:
    Oct 13, 2014
    Posts:
    7
    You have all of that information!
     
  8. Mike-Geig

    Mike-Geig

    Unity Technologies

    Joined:
    Aug 16, 2013
    Posts:
    247
    you forgot to drag something onto a property in the inspector. Check there.
     
  9. dean-o

    dean-o

    Joined:
    Oct 13, 2014
    Posts:
    7
    Not that I can see. Could there be any other reason?
     
  10. Mike-Geig

    Mike-Geig

    Unity Technologies

    Joined:
    Aug 16, 2013
    Posts:
    247
    A null reference means that it is trying to access something that doesn't exist. You either forgot to drag something in the editor, or you are a step ahead and have something un-commented that should still be commented. Your code is using something that isn't there.
     
  11. Pirs01

    Pirs01

    Joined:
    Sep 30, 2012
    Posts:
    389
    You misunderstood me. I'm not gonne go check out some tutorials you're doing and then follow your scarse clues to figured out what is going on exactly in your project because you don't feel like positing detailed description of your problem. I don't get paid for this you know... If you posted the code and the rest of the details I asked for we would tell you exactly what the problem is but if you don;t want to be helped then I'm not gonne insist.
     
  12. kivakabuto

    kivakabuto

    Joined:
    Oct 13, 2014
    Posts:
    2
    i did to drag the enemy attack script and enemy movement to zombunny.. the same like i did drag the player health to player in hierarchy.. and i try to look over again the tutorial but the same error keep happening
     
  13. Degrath

    Degrath

    Joined:
    Dec 19, 2014
    Posts:
    5
    I have the exact same problem
    NullReferenceException: Object reference not set to an instance of an object
    EnemyAttack.Update () (at Assets/Scripts/Enemy/EnemyAttack.cs:54)

    plus the zombunny moves only to the starting location of the player and just walks in place like he is stuck. Attacks do not happen when I run into the bunny nor does the health update in the slider when I manually change the players starting health.
    Unity Version 4.6.1f1 on Tutorial project Survival Shooter. I am following along with the videos and I have started over 3 times. The only code I have typed myself (as per the videos) is PlayerMovement and CameraFollow scripts, all other code came from the project package and is included below in the spoiler.

    Code (CSharp):
    1.  
    2. using UnityEngine;
    3.  
    4. public class PlayerMovement : MonoBehaviour
    5. {
    6.     public float speed = 6.0f;
    7.  
    8.     Vector3 movement;
    9.     Animator anim;
    10.     Rigidbody playerRigidbody;
    11.     int floorMask;
    12.     float camRayLength = 100.0f;
    13.  
    14.     void Awake()
    15.     {
    16.         floorMask = LayerMask.GetMask ("Floor");
    17.         anim = GetComponent<Animator> ();
    18.         playerRigidbody = GetComponent<Rigidbody> ();
    19.  
    20.         }
    21.  
    22.     void FixedUpdate()
    23.     {
    24.         float h = Input.GetAxisRaw ("Horizontal");
    25.         float v = Input.GetAxisRaw ("Vertical");
    26.  
    27.         Move (h, v);
    28.         Turning ();
    29.         Animating (h, v);
    30.         }
    31.  
    32.     void Move(float h, float v)
    33.     {
    34.         movement.Set (h, 0f, v);
    35.         movement = movement.normalized * speed * Time.deltaTime;
    36.         playerRigidbody.MovePosition (transform.position + movement);
    37.     }
    38.  
    39.     void Turning()
    40.     {
    41.         Ray camRay = Camera.main.ScreenPointToRay (Input.mousePosition);
    42.         RaycastHit floorHit;
    43.         if (Physics.Raycast (camRay, out floorHit, camRayLength, floorMask)) {
    44.             Vector3 playerToMouse = floorHit.point - transform.position;
    45.             playerToMouse.y = 0f;
    46.             Quaternion newRotation = Quaternion.LookRotation(playerToMouse);
    47.             playerRigidbody.MoveRotation(newRotation);
    48.         }
    49.     }
    50.  
    51.     void Animating(float h, float v)
    52.     {
    53.         bool walking = h != 0f || v != 0f;
    54.         anim.SetBool ("IsWalking", walking);
    55.     }
    56. }
    57.  
    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. public class EnemyMovement : MonoBehaviour
    6. {
    7.     Transform player;
    8.     //PlayerHealth playerHealth;
    9.     //EnemyHealth enemyHealth;
    10.     NavMeshAgent nav;
    11.  
    12.  
    13.     void Awake ()
    14.     {
    15.         player = GameObject.FindGameObjectWithTag("Player").transform;
    16.         //playerHealth = player.GetComponent <PlayerHealth> ();
    17.         //enemyHealth = GetComponent <EnemyHealth> ();
    18.         nav = GetComponent <NavMeshAgent> ();
    19.     }
    20.  
    21.  
    22.     void Update ()
    23.     {
    24.         //if(enemyHealth.currentHealth > 0 && playerHealth.currentHealth > 0)
    25.         //{
    26.         nav.SetDestination(player.position);
    27.         //}
    28.         //else
    29.         //{
    30.         //    nav.enabled = false;
    31.         //}
    32.     }
    33. }
    34.  
    35.  
    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.  
    82.     public void RestartLevel ()
    83.     {
    84.         Application.LoadLevel (Application.loadedLevel);
    85.     }
    86. }
    87.  
    88.  
    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.  
    82.     public void RestartLevel ()
    83.     {
    84.         Application.LoadLevel (Application.loadedLevel);
    85.     }
    86. }
    87.  
    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. public class CameraFollow : MonoBehaviour {
    6.  
    7.     public Transform target;
    8.     public float smoothing = 5f;
    9.  
    10.     Vector3 offset;
    11.     void Start()
    12.     {
    13.         offset = transform.position - target.position;
    14.     }
    15.  
    16.     void FixedUpdate()
    17.     {
    18.         Vector3 targetCamPos = target.position + offset;
    19.         transform.position = Vector3.Lerp(transform.position, targetCamPos, smoothing * Time.deltaTime);
    20.     }
    21. }
    22.  
    23.  
    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. public class EnemyAttack : MonoBehaviour
    6. {
    7.     public float timeBetweenAttacks = 0.5f;
    8.     public int attackDamage = 10;
    9.  
    10.  
    11.     Animator anim;
    12.     GameObject player;
    13.     PlayerHealth playerHealth;
    14.     //EnemyHealth enemyHealth;
    15.     bool playerInRange;
    16.     float timer;
    17.  
    18.  
    19.     void Awake ()
    20.     {
    21.         player = GameObject.FindGameObjectWithTag ("Player");
    22.         playerHealth = player.GetComponent <PlayerHealth> ();
    23.         //enemyHealth = GetComponent<EnemyHealth>();
    24.         anim = GetComponent <Animator> ();
    25.     }
    26.  
    27.  
    28.     void OnTriggerEnter (Collider other)
    29.     {
    30.         if(other.gameObject == player)
    31.         {
    32.             playerInRange = true;
    33.         }
    34.     }
    35.  
    36.  
    37.     void OnTriggerExit (Collider other)
    38.     {
    39.         if(other.gameObject == player)
    40.         {
    41.             playerInRange = false;
    42.         }
    43.     }
    44.  
    45.  
    46.     void Update ()
    47.     {
    48.         timer += Time.deltaTime;
    49.  
    50.         if(timer >= timeBetweenAttacks && playerInRange/* && enemyHealth.currentHealth > 0*/)
    51.         {
    52.             Attack ();
    53.         }
    54.  
    55.         if(playerHealth.currentHealth <= 0)
    56.         {
    57.             anim.SetTrigger ("PlayerDead");
    58.         }
    59.     }
    60.  
    61.  
    62.     void Attack ()
    63.     {
    64.         timer = 0f;
    65.  
    66.         if(playerHealth.currentHealth > 0)
    67.         {
    68.             playerHealth.TakeDamage (attackDamage);
    69.         }
    70.     }
    71. }
    72.  
    73.  


    Edited to add EnemyAttack script. (which I did not write it was included in the tutorial package with all the other complete scripts)
     
    Last edited: Dec 19, 2014
  14. Random_Civilian

    Random_Civilian

    Joined:
    Nov 5, 2014
    Posts:
    55
    In your case the error is occurring in nemyAttack.cs@ line 54, which, unless I am missing something, you did not post...
    EDIT: Also, shot in the dark, but try seeing if messing with script execution order fixes anything.
     
  15. Degrath

    Degrath

    Joined:
    Dec 19, 2014
    Posts:
    5
    I don't know how or why but after much frustration I decided to stop and I saved and closed the project. When I came back and reopened the project it worked just fine with no errors. I then opened the previous 4 projects I had tried that all had the same error and they all worked with no error as well. I am going to call this one solved for myself. thanks for the help
     
    no1siddharthsharma and vojzzo like this.
  16. Alicedelic

    Alicedelic

    Joined:
    Dec 30, 2014
    Posts:
    1
    "NullReferenceException: Object reference not set to an instance of an object EnemyMovement.Update () (at Assets/Scripts/Enemy/EnemyMovement.cs:23)"

    I had the same problem, in my case it was because I had dragged the enemyHealth(or playerHealth) script twice. Once in the correct place but also onto some other game object other than where it was supposed to go. Causing a duplicate component where it shouldn't have been.

    Caused by a faulty mouse that failed to drag correctly.
     
  17. kamran-bigdely

    kamran-bigdely

    Joined:
    Jun 19, 2014
    Posts:
    25
    I have the same issue(same error message). I have put EnemyHealth script as aproperty of Zombunny but somehow the line:

    enemyHealth = GetComponent <EnemyHealth> ();
    returns null.
     
  18. Argirios

    Argirios

    Joined:
    Jul 13, 2013
    Posts:
    10
    I don't know about the tutorial but this is what the code looks like from your post:

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class EnemyMovement : MonoBehaviour
    5. {
    6. Transform player;
    7. PlayerHealth playerHealth;
    8. EnemyHealth enemyHealth;
    9. NavMeshAgent nav;
    10.  
    11.  
    12. void Awake ()
    13. {
    14. player = GameObject.FindGameObjectWithTag ("Player").transform;
    15. playerHealth = player.GetComponent <PlayerHealth> ();
    16. enemyHealth = GetComponent <EnemyHealth> ();
    17. nav = GetComponent <NavMeshAgent> ();
    18. }
    19.  
    20.  
    21. void Update ()
    22. {
    23. if(enemyHealth.currentHealth > 0 && playerHealth.currentHealth > 0)
    24. {
    25. nav.SetDestination (player.position);
    26. }
    27. else
    28. {
    29. nav.enabled = false;
    30. }
    31. }
    32. }
    Did you add the "Player" Tag to the Player in the inspector? I'd say you did but just check again.
    Since your error seems to be on line 23 the error should be with this:
    Code (CSharp):
    1. if(enemyHealth.currentHealth > 0 && playerHealth.currentHealth > 0)
    Either enemyHealth is null or playHealth is null or both.

    Try deleting or commenting out each one at a time.
    So Replace it with
    Code (CSharp):
    1. if(enemyHealth.currentHealth > 0)
    Test if that has an error if so you aren't referencing enemyHealth properly. Then
    Code (CSharp):
    1. if(playerHealth.currentHealth > 0)
    Test if that has an error if so you aren't referencing playerHealth properly.

    I don't know if you are using Unity Pro but I don't know if you can use the NavMesh without it (maybe if the tutorial says you can then that is OK) otherwise try commenting out those "nav" lines.
     
  19. falcon0172

    falcon0172

    Joined:
    Jan 29, 2015
    Posts:
    3
    Still having error
     
  20. Agustin Bustamante

    Agustin Bustamante

    Joined:
    Mar 7, 2015
    Posts:
    1
    my enemy don't move and I get the same error, anyone can write the correct script?
     
  21. Jural

    Jural

    Joined:
    May 12, 2013
    Posts:
    1
    If anyone is interested, I've found the solution to this issue.

    Recreate:
    Using Unity 5 following Beginner Survival shooter

    Errors:
    1. Enemy moves to players initial starting point and will not follow player
    2. Enemy will not attack

    Debug:
    Both errors are because the position of the Player never moves. If in the script EnemyMovement.cs, function FixedUpdate, you add:
    Debug.Log( "Player Location: " + player.position);
    You will see the Player object always has a position of (0.0,0.0,0.0) even when you are moving the character.​
    Solution:
    In UNITY editor select your Player object. Now add a component of:
    Physics -> Mesh Collider
    Once added check Convex and Is Trigger. The scripts should now work.
    Sorry about how much I wrote. I'm a beginner at Unity3d, and this took awhile to figure out and I though I'd share how I debugged it for other beginners.

    I hope it helps someone.

    *Edit language "start position never moves"
     
    Last edited: Mar 15, 2015
  22. Rhizomorph

    Rhizomorph

    Joined:
    Mar 11, 2015
    Posts:
    1
    I had a problem with "NullReferenceException: Object reference not set to an instance of an object EnemyAttack.Update () (at ssets/Scripts/Enemy/EnemyAttack.cs:54)"

    What finally fixed my problem was checking what I had tagged as "Player"; I had assigned that tag to the "Player" child within the "Player" object within the hierarchy. When I untagged the child then tagged the parent everything worked fine.
     
  23. Shredov

    Shredov

    Joined:
    Mar 24, 2014
    Posts:
    14
    I'm still getting this error....
    Error
    NullReferenceException: Object reference not set to an instance of an object
    EnemyMovement.Update () (at Assets/Scripts/Enemy/EnemyMovement.cs:35)

    I have triple checked and can confirm that the the player object has the PlayerHealth and PlayerMovement scripts, and the Zombunny has EnemyMovement, EnemyAttack, and EnemyHealth scripts attached as well. There is nothing left to drag in since all the values are supposed to be added in the scripting itself.

    I added this just to see what is wrong
    Code
    if ( player == null)
    Debug.Log("player variable is null");

    if ( playerHealth == null)
    Debug.Log("playerHealth variable is null");

    if ( enemyHealth == null)
    Debug.Log("enemyHealth variable is null");

    if ( nav == null)
    Debug.Log("nav variable is null");

    And received the message "enemyHealth variable is null"...
    This makes NO sense to me right now because I am looking right now at the Zombunny object and can see that the EnemyHealth script is attached and I've even looked in the script (which I haven't edited at all) and can see that everything's in there....

    Can someone please tell me what I could possibly be missing, because at this point I'm completely confused.
     
  24. Shredov

    Shredov

    Joined:
    Mar 24, 2014
    Posts:
    14
    Ok... I 'fixed' the issue..

    I dragged another copy of the EnemyHealth script into the inspector... and yes, I already had the script in there so now there's two... I'm now staring at a zombunny with two of the same script, and for some reason its actually working now despite making NO other changes... I don't get it and I want to punch my head through a wall....

    I think I'll just accept it and go to bed now...
     
  25. borraccio

    borraccio

    Joined:
    Mar 28, 2015
    Posts:
    1
    Hi, please help me .. my enemy attack my player , is following him, but my sidebar it doesn't move, there is not a red flash for damage and the player doesn't die. I checked every step . i'm lost, everything look right . thanks
     
  26. Zigec9

    Zigec9

    Joined:
    Apr 6, 2015
    Posts:
    1
    The problem is you didn`t tag your character as Player. Just do this and everything shoul work OK.
     
    Sakuwwz likes this.
  27. khaled.cmps

    khaled.cmps

    Joined:
    May 22, 2015
    Posts:
    1
    In the Survival shooter project there are two folders with scripts having the same name, one is simply called Assets>Scripts, the other is Assets>CompletedAssets>Scripts. Make sure that both files you dragged to the player and to the Enemy are from the same directory. I.e. drag both PlayerShooting and EnemyHealth from the same place, otherwise when you use GetComponent, the script will try to reference the component from the same directory, and thats why the script is not being detected/
     
    thejjr, patnaoum and vmpm like this.
  28. Sagehorn

    Sagehorn

    Joined:
    May 17, 2014
    Posts:
    2
    Thanks man. That's it! But have I really done this? ^^
     
    adnanismajli92 likes this.
  29. Euskalcraft

    Euskalcraft

    Joined:
    May 12, 2014
    Posts:
    1
    Hi

    I have same problem with nav mesh agent and NullReferenceException. For some reason script doesn't find navmesh component.

    I have simple solution and WORKS for mi. Make NavmeshAgent nav variable and player transform Public, then drag and drop enemy and player from de editor to the script.

    public Transform player;
    public NavMeshAgent nav2;

    Delete awake references.


    tell me if it works
     

    Attached Files:

    Last edited: Jun 11, 2015
  30. adolf.ak47

    adolf.ak47

    Joined:
    Jul 20, 2015
    Posts:
    1
    PROBLEM SOLVED ..though i know its too late to reply ...
    by default..the environment is tagged as "Player" in the inspector menu ... change it to untagged...and you're done
     
  31. BruceA117

    BruceA117

    Joined:
    Jul 17, 2015
    Posts:
    1
    Hello Everyone,

    I solved the Enemy Attack issue in the following way. Within the "Enemy Movement" script, two lines were greyed out.

    upload_2015-8-25_12-25-28.png

    Lines 7 and Lines 15 refer to the PlayerHealth script. After un-commenting these lines, the player's health depleted as it should upon colliding with the Zombunny. The EnemyMovement code looked like this after.

    upload_2015-8-25_12-27-54.png

    I hope this fixes your issue.

    -Bruce
     
  32. uplink2501

    uplink2501

    Joined:
    Dec 28, 2015
    Posts:
    1
    This solution worked for me! I had earlier tagged both the parent child and parent object......tricky to find when one is debugging the code and object component settings! THANKS!
     
  33. vojzzo

    vojzzo

    Joined:
    Feb 4, 2016
    Posts:
    1
    Omg this actually worked for me, thanks!
     
  34. kenmoore

    kenmoore

    Joined:
    Jan 4, 2016
    Posts:
    3
    FIXED via khaled.cmps's comment #27 above ... thank you so much!
     
  35. arefin_siam98

    arefin_siam98

    Joined:
    Mar 20, 2016
    Posts:
    5
    Hello, I am facing that same kind of problem and being a very beginner in C# ,i can't figure out what to do ,and have been following "Survival Shooter Tutorial"

    MY en_attack script is :

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;

    3. public class e_attack : MonoBehaviour {
    4. public float timeBA= 0.5f;
    5. public int am=10;
    6. Animator anim;
    7. GameObject player;
    8. float timer;
    9. p_health health_script;
    10. bool inRange;

    11. // Use this for initialization
    12. void Awake () {
    13. player = GameObject.FindGameObjectWithTag ("Player");
    14. health_script = GetComponent<p_health> ();
    15. anim = GetComponent<Animator> ();
    16. }
    17. void OnTriggerEnter(Collider other){
    18. if (other.gameObject == player) {
    19. inRange=true;
    20. }
    21. }
    22. void OnTriggerExit(Collider other){
    23. if (other.gameObject != other) {
    24. inRange=false;
    25. }
    26. }



    27. // Update is called once per frame
    28. void Update () {
    29. timer += Time.deltaTime;
    30. if (timer >= timeBA && inRange) {
    31. Attack();
    32. }
    33. if (health_script.c_h <= 0) {
    34. anim.SetTrigger("PlayerDead");
    35. }

    36. }
    37. void Attack(){
    38. timer = 0f;
    39. if (health_script.c_h > 0) {
    40. health_script.TakeDam(am);
    41. }


    42. }
    43. }
    HERE :p_health is a script i attached to my player. And continuously getting the following error :
    NullReferenceException: Object reference not set to an instance of an object
    e_attack.Attack () (at Assets/e_attack.cs:47)
    e_attack.Update () (at Assets/e_attack.cs:37)
    As i've figured out these two lines are -
    47 : if (health_script.c_h > 0)
    37: Attack();

    Please Help, I am stuck there :'( :( :(
     
  36. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    stop necro'ing old threads about this basic issue when you have a reply already in a previous one... :p
     
  37. arefin_siam98

    arefin_siam98

    Joined:
    Mar 20, 2016
    Posts:
    5
    I am badly in need of this solution .Sorry
     
  38. onzicardz

    onzicardz

    Joined:
    Nov 5, 2015
    Posts:
    3

    Hey Thanks this worked "tagged as "Player"; "
    The little things that can be missed ;-)
    It really helps with the learning.
    Thanks
     
  39. OuakkahaAyoub

    OuakkahaAyoub

    Joined:
    Jun 16, 2016
    Posts:
    2
    Same here ..
    I fixed it by restarting untiy :) some times the simple way is the best solution :) Have fun
     
  40. alexnavarrogarcia78

    alexnavarrogarcia78

    Joined:
    Jul 3, 2016
    Posts:
    1
    You're awesome!!!! That worked for me too.... Little details that can keep you awake at nights :)
     
  41. yalavarthijaideep

    yalavarthijaideep

    Joined:
    Aug 2, 2016
    Posts:
    7
    It is giving
    NullReferenceException: Object reference not set to an instance of an object
    EnemyAttack.Update () (at Assets/Scripts/Enemy/EnemyAttack.cs:63)
     
  42. RavenOfCode

    RavenOfCode

    Joined:
    Apr 5, 2015
    Posts:
    869
    NullReferenceException means that something is null (meaning has no value), when it says :63 that means thats the line its at. Simple find what is null then give it a value.
     
  43. yalavarthijaideep

    yalavarthijaideep

    Joined:
    Aug 2, 2016
    Posts:
    7
    The player is not dying after the health is over
     
  44. yalavarthijaideep

    yalavarthijaideep

    Joined:
    Aug 2, 2016
    Posts:
    7
    It is giving NullReferenceException: Object reference not set to an instance of an object PlayerHealth.Death () (at Assets/Scripts/Player/PlayerHealth.cs:86)
    Please help
     
  45. RavenOfCode

    RavenOfCode

    Joined:
    Apr 5, 2015
    Posts:
    869
    Its because something is null. You are trying to use that something at line 86, what is line 86?
     
  46. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    you might notice all that raven is doing is rewording what the error text is saying. This is because you're not giving us anything else to work with.

    Just because this thread was about a "null ref error" doesn't in any way mean your problem has anything to do with it. Null ref errors are so generic it's basically saying "something which should be there isn't" which is completely dependent on what code you've written.

    You'd do far better with opening a new thread (rather than jumping on one from a couple of years ago), explaining what you are trying to do, showing what code you have (http://forum.unity3d.com/threads/using-code-tags-properly.143875/) and giving the error there so we can see what line is going wrong.

    Then we can help.
     
    RavenOfCode likes this.
  47. Ben_Huang4163

    Ben_Huang4163

    Joined:
    May 25, 2016
    Posts:
    1
    thanks! you are correct, and your solution is work! if anybody had the same problem, had tried the other solution above and doesn't work, then you should try this one. Or just simply change the script name "enemyMovement" instead of "EnemyMovement" or any other name but different from the original name. it should solve the problem.
    the unity tutorial update doc should give us a warning, so that we don't need waste time on it.
     
  48. Boruta

    Boruta

    Joined:
    Jul 29, 2015
    Posts:
    1
    I've just managed to deal with that problem.

    As was suggested above, I accidentally attached the EnemyManager script to other gameobject.

    IMO the easiest solution is to simply add

    Debug.Log(this.gameObject);

    to the code that generates the problem to find the "guilty" gameobject
     
  49. abapandy

    abapandy

    Joined:
    Feb 18, 2017
    Posts:
    1
    I know this is an old thread, apologies if a fix exists in another thread, but khaled.cmps's comment #27 above helped fix the issue (in Unity 5.5) for me although my issue was caused by a slight variation (my fault) - my symptoms were:
    • Got the NullReferenceException in 2 places - line 65 of EnemyAttack and line 27 of EnemyMovement
    • Zombear and Hellephant were spawning but always got stuck at their spawnPoint, and I could not shoot them
    • Zombunnies seemed to be working properly
    My steps to determine the cause were:
    1. Realized the Null exception meant a bad object reference was occurring - I first tried adding code to only use player in the EnemyAttack / EnemyMovement code if (player != null). Still received the same errors
    2. In the EnemyManager object (in Unity), I de-activated the EnemyManager scripts for Zombear and Hellephant. When I ran, Zombunny objects were spawned just fine with no errors - this led me to believe the issue was with one/both of the other enemy types
    3. De-activated Zombunny from the EventManager object in Unity then activated Zombear. Running the game produced the errors for just the Zombear. I noticed (despite my additional lines of code), the errors were always reported as lines 65 and 27 which didn't make sense given that I'd added new lines of code - with 1 new line of code, the line 65 error should have become 66 if my version of the code was being executed. Then I noticed this in the actual error messages:
    NullReferenceException: Object reference not set to an instance of an object
    CompleteProject.EnemyAttack.Update () (at Assets/_CompletedAssets/Scripts/Enemy/EnemyAttack.cs:65)
    To fix, I opened up the prefab for Zombear and deleted the scripts from it. I then dragged the EnemyAttack, EnemyMovement and EnemyHealth scripts from the /Scripts (NOT Completed/Scripts) folder into the Zombear prefab. When I re-ran, the enemy spawning, movement attack and ability to damage/kill were fixed.
    Note that the properties for the Zombear and Hellephant should be checked/updated manually after re-attaching the correct scripts and the correct Death Clip needs to be re-selected with the circle-selector.
    I repeated the same thing for the Hellephant prefab and (after re-enabling scripts for all 3 enemy types in the EnemyManager game object) all is now working without the NullReferenceException errors.

    I think I was too lazy when I added Zombear and Hellephant enemies - I simply dragged those prefabs (which had the scripts attached already) from the completed folder - I think that is why the script locations were getting messed up for me.

    Hope this helps someone else.
     
  50. AlejoR

    AlejoR

    Joined:
    Apr 19, 2017
    Posts:
    1
    Thanks a lot abapandy, I was stock with exactly the same issue, same lines of code and everything, you save me a lot of time.
    cheers
     
    Irfankhan971 likes this.
Thread Status:
Not open for further replies.