0

new poster and new to stack exchange. I apologise if this has been answered but i am unable to find a solution sifting through the posts here.

I am getting a null reference exception on a very basic health bar script.

HealthBar script:

using UnityEngine;
using System.Collections;
using UnityEngine.UI;


public class HealthBars : MonoBehaviour {

    public GameObject pug;
    private Animator animator;

    public Slider healthBar;
    public Slider waterBar;
    public Slider poopBar;
    public Slider weeBar;
    public Slider foodBar;

    public static int health = 100;
    public static int wee = 0;
    public static int food = 25;
    public static int poop = 0;
    public static int water = 50;

    // Use this for initialization
    void Start()
    {



        InvokeRepeating("ReduceFood", 1, 1);
        InvokeRepeating("WaterDrain", 1, 1);




    }

    // Update is called once per frame
    void Update ()
    {

    }

    void ReduceFood()
    {
        food = food - 5;
        foodBar.value = food;
    }

    void WaterDrain()
    {
        water = water - 2;
        waterBar.value = water;
    } 

I have the script attached to an empty GameObject. It drains the food once then throws the exception?

Scott Chamberlain
  • 116,967
  • 28
  • 260
  • 389
  • Did you already assign those public variables like healthBar, waterBar? – Trafalgar Apr 18 '17 at 03:29
  • I dont think so? Strange thing is, it was working then decided to stop after utilising them in an OnCollisionEnter script. – CrayzyHayzy Apr 18 '17 at 11:57
  • Alrighty guys, Clark, thanks for the help but I have it solved. As it turns out it was a very simple and stupid error on my part, not even code related. A copy of the script had somehow attached itself to another GameObject (static one) and was throwing the null exception because the publicy exposed fields were not intantiated. – CrayzyHayzy Apr 19 '17 at 01:54

0 Answers0