player on fire timer

I am trying to create a timer that begins when player OnTriggerEnter an object with the tag fire. The timer counts to 5, then resets. It is going to be used to reduce player health for a short time after player has come into contact with fire game object.

It works fine apart from when the counter resets it then won’t start again if player OnTriggerEnter a second time.

I’m sure it’s something very simple that I’m not yet aware of in Unity but I’m new coding. Any help/advice would be appreciated.

Thanks very much.

Here is the code:

var playerHealth : int = 100;


var onFire : boolean = false;
var flameTimer : int = 0;


function Start () {


}


//Tells script player has collided with fire//////////

function OnTriggerEnter(other : Collider){

	if(other.gameObject.CompareTag("fire")){
		
		onFire = true;
						
	}

}

//Converts player health to string and puts it in GUI element////////////////
function OnGUI (){
	GUI.Label (Rect (10, 10, 100 ,20), "Health: " + playerHealth.ToString());
	GUI.Label (Rect (10, 20, 100, 20), "flameTimer: " + flameTimer.ToString());
	GUI.Label (Rect (10, 30, 100 ,20), "onFire: " + onFire.ToString());
}


function Update () {

   if (onFire == true){
    
    	flameTimer = Time.time;//increments flameTimer up
    	playerHealth = 100 - flameTimer;//increments playerHealth down
    	
    }
    
    if (flameTimer >= 5){//if flameTimer is greater than or equal to 5 then stop player being on fire
    
    	onFire = false;
    
    }


}//UPDATE END

Maybe you should try using the InvokeRepeating method.

InvokeRepeating("Fire", 0, flameTime);

Then, to cancel firing, call CancelInvoke.

CancelInvoke("Fire");

Of course, you’ll need a Fire method:

function Fire()
{
    // firing logic goes here
}

Thank you slayer29179 and iwaldrop. Much appreciated. In the end I found a different approach which may be of interest.

I used a yield WaitForSeconds (5); http://docs.unity3d.com/Documentation/ScriptReference/WaitForSeconds-ctor.html

Ended up being a tidy way to write it. It’s not that precise, I end up removing 6-7 points from player health but for the time being it will do.

Thanks again for the help :slight_smile:

Here it is:

var playerHealth : int = 100;



//TRAPS DAMAGE///////////////////////////////////
var onFire : boolean = false;




//on fire timer
function OnTriggerEnter(other : Collider){

	if(other.gameObject.CompareTag("fire")){
		
		onFire = true;
		yield WaitForSeconds (5);//wait for 5 seconds
		onFire = false;
						
	}

}


function Start () {


}//START END///////////////////////////////////






//Converts player health to string and puts it in GUI element////////////////
function OnGUI (){
	GUI.Label (Rect (10, 10, 100 ,20), "Health: " + playerHealth.ToString());
	GUI.Label (Rect (10, 30, 100 ,20), "onFire: " + onFire.ToString());
}





function Update () {


//Flame ///////////////

if (onFire == true){

	playerHealth = 100 - Time.time;

}




}//UPDATE END