How do I use a trigger to start a piece of code?

Hi I have a piece of code which takes damage from a player incrementally, like this:

InvokeRepeating("subtract", 2, 0.5);

function subtract() 
    HEALTH -=1;
    print ("health is now " + HEALTH);

However I would only like this code to run once a player has entered a certain area. If I was to put a trigger over the entrance to that area, how would I get it to make this code run, and continue to run even if the player moves out of the trigger?

(I'm sure this is pretty simple but I'm not at all good with code and I'm just trying to get to grips with it!)


If you want it to continue to run, you tag your area trigger as "DangerArea", and then add something like this code on your player:

var healthIsDraining = false;

function OnTriggerEnter(otherCollider : Collider) {

    if (otherCollider.tag == "DangerArea") {

        if (!healthIsDraining) {
            InvokeRepeating("subtract", 2, 0.5);
            healthIsDraining = true;


Note, I added a "healthIsDraining" flag so that the "subtract" function isn't started up again if you enter the collider a second time. Otherwise you'd have multiple repeating calls to "subtract" overlapping each other and the health would drain away even faster!