I need a health bar that decreases proportionately with the player’s vitality, but the script has given the error “An instance of type ‘healthBar’ is required to access non static member ‘fgImage’”.
I have been through the forums (I know that there are so many health bar related questions) - but I still can’t work out how to make the health bar work properly.
Here is the health bar script:
var energyBar : GUIStyle ;
var bgImage : Texture2D;
var fgImage : Texture2D;
static var playerEnergy = 1.0;
var maxHealth : int = 100.0;
var curHealth : int = 70.0;
var percentHealth : Number = curHealth / maxHealth;
function Start() {
}
function Update() {
}
function OnGUI () {
GUI.BeginGroup (Rect (10,10,256,32));
GUI.Box (Rect (0,0,256,32), bgImage, energyBar);
GUI.BeginGroup (Rect (0,0,playerEnergy * 256, 32));
GUI.Box (Rect (0,0,256,32), fgImage, energyBar);
GUI.EndGroup ();
GUI.EndGroup ();
}
function updateHealthBar () : void
{
percentHealth = curHealth / maxHealth;
healthBar.fgImage.ScaleX = percentHealth;
}
If anyone has the time to point out how to sort out the errors I would be so grateful.
Thanks in advance, Laurien
Try change the maxHealth and curHealth to floats.
Unity doesn’t like dealing with integers for percentages.
— Then —
Replace your healthBar.fgImage.ScaleX
to
healthBar.fgImage.transform.scale.x
OK. The debug line says exactly what is wrong. You do not have an instance of healthBar available so your code is accessing fgImage as a static variable. Instead of:
healthBar.fgImage.ScaleX = percentHealth;
try this:
fgImage.ScaleX = percentHealth;
Hopefully that will remedy the static reference error.