I have an error, plz help!

this is my code:
public Image HealthBar;
public Image FoodBar;
public Image WaterBar;
float Health = 1f;
float Food = 0.8f;
float Water = 0.8f;

void Start () {

}

void Update () {
HealthBar.fillAmount = Health;
FoodBar.fillAmount = Food;
WaterBar.fillAmount = Water;

Health = Time.deltaTime * 2;
}

this is the error i get:

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

sorry for the bad code tags, not sure how to use them…

does anyone know how to fix this?
thank you.

Code tags are pretty easy!

Here’s a good explanation of what a nullref is!

What line do you get the error on? And please edit the code with code tags.

I suspect you have not assigned an image in the Inspector.

Also, this isn’t really doing anything useful. If you want health to go up/down over time you add/subtract from it (-= and +=). You’re just setting it to = time.deltatime * 2 so it’s just going to sit at some tiny amount.

3 Likes

God mode, always on the edge of death but still immortal :smile:

ive added this to void start()

HealthBar = GameObject.Find(“FPSController”).transform.FindChild(“FirstPersonCharacter”).FindChild(“Canvas”).FindChild(“healthBar”).GetComponent();
HealthBar.fillAmount = Health;

FoodBar = GameObject.Find(“FPSController”).transform.FindChild(“FirstPersonCharacter”).FindChild(“Canvas”).FindChild(“foodBar”).GetComponent();
FoodBar.fillAmount = Food;

WaterBar = GameObject.Find(“FPSController”).transform.FindChild(“FirstPersonCharacter”).FindChild(“Canvas”).FindChild(“waterBar”).GetComponent();
WaterBar.fillAmount = Water;

what do i need to do to fix it?

Why not just drag-and-drop what you need onto the Inspector? GameObject.Find has a bad reputation for being slow.

1 Like

First of all, when looking at this code you should immediately recognize you’re doing redundant / unnecessary operations.
Secondly, method chaining like you’ve done it in this example is often prone to errors, at least if the given context does not ensure the accessed members do always exist. As you can easily do typos (e.g. game objects names), object renaming/deleting/adding, this is not a safe context at all.

Last but not least, you can assign the variables via Unity inspector.

1 Like