I've tried a few different ways but haven't found anything which seems to work perfectly.
Basically, on collision I want to do a method for say 20 seconds. I've tried various while loop examples but they seem to crash.
If anyone can point me in the right direction it would be much appreciated.
I would do something similar to this:
bool looping = false;
public int loopTime;
void OnCollisionEnter () {
if(!looping) {
//this just prevents it from being called while it is already looping.
StartCoroutine( CollisionLoop(loopTime) );
}
}
IEnumerator CollisionLoop (int loopLength ) {
float i = 0;
looping = true;
while (i <= loopLength) {
//Run Loop;
i += Time.deltaTime;
//add 1 frame's length to i.
yield return null;
//wait one frame
}
looping = false;
}
After each frame, we add the change in time since the last frame, deltaTime, to `i`. So after 1 second, the deltaTime will be (approximately) 1. Then we wait a frame and repeat the loop if `i` is less than loop time. So as long as `i` is less than `loopLength` seconds, you will run the loop again. The `looping` check is just there so that if you bump an object twice you won't start 2 loops. That would more than likely be bad.