Looping OnTriggerStay. How can I repeat this script indefinetly?

Hi all,

I am trying to get the following script to simply repeat itself indefinitely.
At the moment it only cycles through once.

Any suggestions?

Thanks,

Greg

function OnTriggerStay (other : Collider) {

if (other.attachedRigidbody)
{

other.attachedRigidbody.AddForce (5, 0, 0);
yield WaitForSeconds(2); // wait five seconds
other.attachedRigidbody.AddForce (-5, 0, 0);

}}

OnTriggerStay will continue to run and run and run indefinitely (as long as something’s in the trigger).

Looks to me though, like you add the force, wait for two seconds, and then near-simultaneously you add 5 x and -5 x, resulting in 0 force. From then on, you end up adding 0 force every 2 seconds.

Thanks, Tuah,

I’m using this as a tidal current simulator and wanted to have a back and forth movement
on all rigidbodys i.e fish. This is the reason for the two opposing AddForce lines.
Is there a better way to repeat both AddForce lines to simulate a tidal current?

Thanks,

Greg

Still looking for an answer to this.
Any ideas?

You have to be a little more specific. Do you just want the fish to have this effect forever from the start of the scene? If that’s the case just have a single script with the same code in the Update and attach it to the fish prefab.

If you want it to start once it enters a trigger than do the same as above but have it activate OnTriggerEnter with a bool or something.

You could use a InvokeRepeating or Update, and do a raycast or set a bool in OnTriggerEnter. You really should not be using yield in OnTriggerEnter.