New Coder Needs Helps with IEnumerator

Hi I’ have been coding for about a week and I want to add a delay to my code but my IEnumerator doesn’t work does anyone know what’s the problem.

void OnCollisionEnter(Collision collisonInfo) // check what we collide with
{

if (collisonInfo.collider.tag == “Boost”) //checking if boost pad is hit
{
Debug.Log("we got a boost ");

SpeedBoost(); // call function speedboost
}
}
void SpeedBoost()
{

forwardForce = forwardForce * 6; // change force
StartCoroutine(WaitforBoost()); // wait sec

forwardForce = 4000f; // reset force
Debug.Log(“SpeedBoost is over”); // show speed boost is over

}

private IEnumerator WaitforBoost()
{
yield return new WaitForSeconds(6); // wait # of sec

}

A coroutine runs at the same time as everything else. It does not “pause” execution. So your coroutine at this point does nothing but count up 6 seconds in the background while the game is running.

Try moving the code that changes force inside the coroutine. In other words your coroutine should:
Set the force
Wait 6 seconds.
Reset the force.

Right now you are essentially doing:
Set the force.
Start counting 6 seconds but also Immediately Reset the force.

Hope this makes sense.

2 Likes
private IEnumerator WaitforBoost()
{
yield return new WaitForSeconds(6); // wait # of sec
forwardForce = 4000f;
1 Like

thank you

Hi,

You could edit your post to use code tags, then it would be so much easier on the eyes…

You could also make your Coroutine more flexible by passing the item that is to be run as a parameter.
This way you could use the same code for different things you need to delay.
i.e.

void Start()
{
    StartCoroutine(WaitforMoment(AfterWait));
}

IEnumerator WaitforMoment(Action afterWait)
{
    Debug.Log("Start waiting");
    yield return new WaitForSeconds(5);
    afterWait();
}

void AfterWait()
{
    Debug.Log("Wait is over");
}
1 Like