Health Bar Code Help

Hello and thanks for your time!! I have this code in my game, and if u get hit and get to the end point in the level it will restart the level with the amount of health that you finished the level with. I want to somehow make it so when you get to the end of the level and win, when you restart the level it will reset your life back to full.

var health1 : Texture2D; //one life left
var health2 : Texture2D; //two lifes left
var health3 : Texture2D; //Full health

static var LIVES = 3;

function Update () 
{
	switch(LIVES)
	{
		case 3:
			guiTexture.texture = health3;
		break;
		
		case 2:
			guiTexture.texture = health2;
		break;
		
		case 1:
			guiTexture.texture = health1;
		break;
		
		case 0:
			Application.LoadLevel(4);
			LIVES = 3;
		break;		
		
		
	}
}

Shouldn’t reloading the Level automatically reset your lives? Unless you’re saving the variable. Also for case 0 wouldn’t LIVES = 3; go before Application.LoadLevel? One other thing, here’s an easier way to setup an array for any var. Just add 3 slots in the inspector and add the Textures to the dropdown.

var health : Texture2D[]; 
static var LIVES = 3;

 

function Update () 

{

    switch(LIVES)

    {
        case 3:
            guiTexture.texture = health[2];
        break;        
        case 2:
            guiTexture.texture = health[1];
        break;      
        case 1:
            guiTexture.texture = health1[0];
        break;       
        case 0:
            LIVES = 3;
            Application.LoadLevel(4);         
        break;             

    }

}

This is a good start, but let me refine this a bit for you :slight_smile:

var health : Texture2D[]; 
var defaultLifeCount : int = 3;
var levelSelect : int = 4;
static var Lives : int = 3;

function Update () 
{
    if(Lives == 0)
    {
        Lives = defaultLifeCount;
        Application.LoadLevel(levelSelect);
        return;
    }

    guiTexture.textures = health[Lives - 1];
}

Ideally the first thing you would do is check the ‘game over’/‘level select’ condition. From there, everything else is a matter of converting your 1-based life indexes to 0-based array elements. I also refactored significant values into variables such that A) the code reads a little better, and B) you have a little more flexibility in editing this stuff in the editor.

IndexOutOfRangeException: Array index is out of range.
HealthControl.Update () (at Assets/Scripts/HealthControl.js:15)

is the code i’m receiving and also my life bar isn’t going down when im getting hit and re spawning =[

Make sure in the inspector that you have the Texture2D array set to 3 and contains all 3 textures.

wouldnt i just be able to add this to the current code i have now and it should work??

if(Lives == 0)

{

Lives = defaultLifeCount;

Application.LoadLevel(levelSelect);

return;

}