- Home /
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?
Answer by Eric5h5 · Dec 06, 2010 at 01:34 AM
Have OnTriggerEnter be a coroutine:
var timeToRun = 5.0;
function OnTriggerEnter () { var timer = 0.0; while (timer < timeToRun) { // do stuff timer += Time.deltaTime; yield; } }
Thanks a bunch this is what I was trying to do.
Answer by oliver-jones · Dec 06, 2010 at 12:39 AM
This should do the trick:
var timer = 10;
function Update(){ Invoke("TimedFunction", timer); }
function TimedFunction(){ Destroy(gameObject); //---edit---\\ return; }
Putting Invoke in Update will cause a new instance of TimedFunction to be created every frame.
Right you are - you could place a if(timerBool = true) statement before the Invoke
Answer by pyro · Dec 06, 2010 at 12:43 AM
//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 }
Your answer
Follow this Question
Related Questions
Time does not start counting down when need to 1 Answer
Stop and Resume Timer 0 Answers
Unity3D Timer. 1 Answer
Start timer with trigger 1 Answer