Help me, "WaitForSeconds()" not running while loop game

I searched more article about using WaitForSeconds (C# version) but with javascript code, I can run it and review result, but C# not run.

My code above

using UnityEngine;
using System.Collections;

public class Box_Bum : MonoBehaviour {
	
	// Use this for initialization
	IEnumerator Wait () {
	       yield return new WaitInSeconds(0.5f);
	}
	
	// Update is called once per frame
	void OnCollisionEnter (Collision col)
	{
		print(Time.time);
                Wait();
                print(Time.time);
	}
}

I’m using Unity3d 3.0f5 Windows version. Please help me.

A few things are missing here.

  1. You must call a Coroutine with StartCoroutine. Like this:
    StartCoroutine(Wait());
    If you don’t do that the engine will not know what to do with the yield commands, and will run it like a normal function.

  2. Yields only operate within that scope. Coroutines are useful because they allow something to run over multiple frames without blocking the current updating. But you need to clarify what you want to wait and what you want to continue processing. Imagine an example where you put that wait function in Update(). Would you want to continue calling updates each frame? or only every 0,5f seconds. Would you want those Updates to stack up? Having a coroutine halt the calling function would be pretty ambiguous and dangerous. So instead it only halts the element within the Coroutine.

The order is like this:
OnCollisionEnter Starts
Print Time
Wait Starts
Wait runs till Yield
OnCollisionEnter Continues
Print Time
OnCollisionEnter Finishes

In 0.5 seconds Wait Continues
Wait Finishes.

This means you need to place your second print within the wait. And if you want one function to wait for another, you can do this:

public IEnumerator HandleCoroutine()
{
yield return StartCoroutine(Wait());
print(“All Done”);
}

IEnumerator Wait()
{
yield return new WaitForSeconds(0.5f);
}

This will cause HandleCoroutine to wait for the Wait Coroutine (which waits for 0.5 seconds) before continuing to print all done. anything not called with StartCoroutine cannot be processed under multiple frames thorugh Coroutines.

So rememeber if it’s not a coroutine itself it will call it’s entirety on that frame.