x


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!)

Thanks

more ▼

asked Apr 27 '10 at 01:09 PM

Pure Phase gravatar image

Pure Phase
224 21 24 31

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

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!

more ▼

answered Apr 27 '10 at 01:30 PM

duck gravatar image

duck ♦♦
41.4k 95 152 415

Thankyou works perfectly :)

Apr 27 '10 at 02:36 PM Pure Phase
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x3568
x1018

asked: Apr 27 '10 at 01:09 PM

Seen: 1053 times

Last Updated: Apr 27 '10 at 01:23 PM