x


creating a timed function

I'm trying to create a function that will run for a certain amount of time then stop or return on the enter of a trigger. I can't seem to figure out how I'd structure that function to just return how long its been since the trigger was hit. I want to run this function for a set amount of time then make it stop in the most efficient way possible. Any ideas?

more ▼

asked Dec 06, 2010 at 12:30 AM

user-7131 (google) gravatar image

user-7131 (google)
5 4 4 7

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

3 answers: sort voted first

Have OnTriggerEnter be a coroutine:

var timeToRun = 5.0;

function OnTriggerEnter () {
    var timer = 0.0;
    while (timer < timeToRun) {
        // do stuff
        timer += Time.deltaTime;
        yield;
    }
}
more ▼

answered Dec 06, 2010 at 01:34 AM

Eric5h5 gravatar image

Eric5h5
107k 52 180 648

Thanks a bunch this is what I was trying to do.

Dec 06, 2010 at 03:59 AM user-7131 (google)
(comments are locked)
10|3000 characters needed characters left

This should do the trick:

var timer = 10;

function Update(){
Invoke("TimedFunction", timer);
}

function TimedFunction(){
Destroy(gameObject);
//---edit---\\
return;
}
more ▼

answered Dec 06, 2010 at 12:39 AM

oliver-jones gravatar image

oliver-jones
3.8k 696 1169 680

Putting Invoke in Update will cause a new instance of TimedFunction to be created every frame.

Dec 06, 2010 at 01:35 AM Eric5h5

Right you are - you could place a if(timerBool = true) statement before the Invoke

Dec 06, 2010 at 01:10 PM oliver-jones
(comments are locked)
10|3000 characters needed characters left
//run for the first 5 seconds
function Update()
{
    if (Time.time < 5)
    {
       //do code
    }
}

///////////2nd method: run until trigger has been hit 
var triggerHit : boolean = false;

function OnTriggerEnter()
{
   triggerHit = true;
}

function Update()
{
   if (triggerHit) return;

   //do code
}
more ▼

answered Dec 06, 2010 at 12:43 AM

pyro gravatar image

pyro
795 12 9 30

(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:

x844
x539

asked: Dec 06, 2010 at 12:30 AM

Seen: 2273 times

Last Updated: Dec 06, 2010 at 12:30 AM