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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Question beginner problem Help Needed

Discussion in 'Scripting' started by FirstBB8Droid, Jun 1, 2020.

  1. FirstBB8Droid

    FirstBB8Droid

    Joined:
    May 17, 2020
    Posts:
    39
    I'm makeing a unity fps game and I have been trying to implement enemy healthbars above their head. I keep gettting the error
    NullReferenceException: Object reference not set to an instance of an object
    Target.Start () (at Assets/scripts/Target.cs:12)
    and I feel like it's probably a really easy fix but I can't figure it out. here's my Target code

    using UnityEngine;
    using UnityEngine.UI;
    public class Target : MonoBehaviour{

    public float health = 50f;
    public Slider slider;


    void Start()
    {
    slider.value = health;
    }

    void update()
    {
    slider.value = health;
    }
    public void TakeDamage (float ammount)
    {
    health -= ammount;
    if(health <= 0f)
    {
    Die();
    }
    void Die()
    {
    Destroy(gameObject);

    }
    }
    Code (CSharp):
    1.  
    2. using UnityEngine;
    3. using UnityEngine.UI;
    4. public class Target : MonoBehaviour{
    5.  
    6.     public float health = 50f;
    7.     public Slider slider;
    8.    
    9.  
    10.     void Start()
    11.     {
    12.         slider.value = health;
    13.     }
    14.  
    15.     void update()
    16.     {
    17.         slider.value = health;
    18.     }
    19.     public void TakeDamage (float ammount)
    20.     {
    21.         health -= ammount;
    22.         if(health <= 0f)
    23.         {
    24.             Die();
    25.         }
    26.         void Die()
    27.         {
    28.             Destroy(gameObject);
    29.            
    30.         }
    31.     }
    32.  
    if you need any other code, please, just ask
     
  2. MatrixQ

    MatrixQ

    Joined:
    May 16, 2020
    Posts:
    87
    In the Inspector, did you give the slider object to the script? I feel like that might be the object it can't find, which is why it is throwing a null pointer exception.
     
  3. FirstBB8Droid

    FirstBB8Droid

    Joined:
    May 17, 2020
    Posts:
    39
    yeah I had 2 enemy objects and I forgot about one of them
     
  4. FirstBB8Droid

    FirstBB8Droid

    Joined:
    May 17, 2020
    Posts:
    39
    thanks for the help man