Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

I'm trying to make a collider appear every 1 second. But I can't get the code right. I tried enabling the collider in the Update function and putting a yield to make it update every second or so. But it's not working (it gives me an error: Update() cannot be a coroutine.)

How would I fix this? Would I need a timer system to toggle the collider?

var waitTime    : float = 1;
var trigger     : boolean = false;

function Update () {

        if(!trigger){
            collider.enabled = false;
            yield WaitForSeconds(waitTime);
        }
        if(trigger){
            collider.enabled = true;
            yield WaitForSeconds(waitTime);
        }
    }

}
share|improve this question
    
You can't use a coroutine in the Update function. –  Dan the Man Jun 30 '12 at 22:32

1 Answer 1

up vote 2 down vote accepted

That should be rather simple. Just have an accumulator where you add the elapsed time each frame. As soon as the accumulator is greater or equal to your "waitTime", toggle the collider.

Example:

var accumulator:float = 0.0;
var waitTime:float = 1.0;

function Update(){
    accumulator += Time.deltaTime;
    if(accumulator >= waitTime){
        // change enabled from true to false and vice-versa.
        collider.enabled = !collider.enabled;
        accumulator -= waitTime;
    }
}
share|improve this answer
    
How would I delay the start-up of the object with the code? I tried adding another variable to waitTime but it didn't work. –  Blue Jul 1 '12 at 19:36
    
@Blue You could set waitTime to 10.0 initially, then set it to 1.0 in the if block (after accumulator -= waitTime;) –  bummzack Jul 2 '12 at 7:29

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.