0

(Issue is open on GitHub Here)

I am building a health bar for a fighting game in Unity, and for some reason the Health bar text does not appear and all it gives me is a null reference error, yet I've checked that everything it references is not 'null'.

The code for the text is here:

function Update () {
    canvasText.text = brawlers[0].currentHealth + "/" + brawlers[0].myClass.health; 
    canvasText2.text = brawlers[1].currentHealth + "/" + brawlers[1].myClass.health; 
}

The Brawlers array refers to two classes, each of them like this:

#pragma strict

var className : String;
var health : int;
var Attack : int;
var Defense : int;
var Speed : int; 

I created a prefab with only the class attached and gave the health a value of 120. This prefab is attached to the fighters in the game, which are the brawlers array, as the 'myClass' varible. CurrentHealth is a varible initilized in the Brawler class.

I have tried multiple types to trace the parts that wouldn be null in the project but I have not found anything that could mean that this error is thrown.

Why is there a null reference exception then?

Cœur
  • 37,241
  • 25
  • 195
  • 267
JianZen
  • 227
  • 1
  • 5
  • 13
  • possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – maraaaaaaaa Jul 29 '15 at 14:27
  • At least ad your log so we can tell why is your null reference exception is coming. – Nain Jul 29 '15 at 14:43
  • Please provide either a screenshot or copy/paste the console log. – Uri Popov Jul 29 '15 at 14:45
  • [Here](http://prntscr.com/7yfh2p) is a screenshot of the log – JianZen Jul 29 '15 at 15:11
  • If you `console.log` all variables in your Battle.Start method, which one is null? – Kenney Jul 29 '15 at 15:18
  • Looking at your Git, the Battle component you have attached to the Background object is missing a fair few of its values. Health Bar for example. So that is null. I don't know why you say they aren't, so you may want to check how your verified this. In general, if something gives you a null reference exception, it's because something is null. So you better verify. – Bart Jul 29 '15 at 15:43
  • I've verified and now its working. Thx guys for withstanding my incompitance – JianZen Jul 29 '15 at 16:20

1 Answers1

1

Your log clearly shows that their is a null reference exception in Start of Battle.cs script at line 15. Debug the issue by checking how it is assigned if assigned and is there some way that it is destroyed or unassigned.

Zohaib Javed
  • 323
  • 1
  • 20