0
\$\begingroup\$

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);
        }
    }

}
\$\endgroup\$
1
  • \$\begingroup\$ You can't use a coroutine in the Update function. \$\endgroup\$
    – Daniel
    Jun 30, 2012 at 22:32

1 Answer 1

2
\$\begingroup\$

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;
    }
}
\$\endgroup\$
2
  • \$\begingroup\$ 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. \$\endgroup\$
    – Blue
    Jul 1, 2012 at 19:36
  • \$\begingroup\$ @Blue You could set waitTime to 10.0 initially, then set it to 1.0 in the if block (after accumulator -= waitTime;) \$\endgroup\$
    – bummzack
    Jul 2, 2012 at 7:29

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .