Detecting When all rigidBodies have stopped moving

HI,

I have several gameObjects on the screen and they are using physics to fall over and stuff.
What i want to do is have a script that will run to check all the rigidbodies in the current scene has stopped moving or not.
I want it to report back when they have stopped so i can call a level complete function.

I am using c#.

Any advice on this would be good as my current code keeps getting stuck in endless loops.

This is what i have so far.

using UnityEngine;
using System.Collections;

public class BlockAmount : MonoBehaviour {
	
	public int blockAmount;
	public tk2dTextMesh blockText;
	
	public delegate void BlocksAllDoneHandler ( bool congrats );
	public static event BlocksAllDoneHandler AllDone;
	
	// Use this for initialization
	void Start () {
		
		blockAmount = 2;
		
		blockText.text = "" + blockAmount;
		blockText.Commit();
	}
	
	void OnEnable ()
	{
		TouchManager.DestroyBlock += TouchManager_DestroyBlock;	
	}
	
	void TouchManager_DestroyBlock( int  block )
	{
		blockAmount -= block;
		blockText.text = "" + blockAmount;
		blockText.Commit();
		
		if ( blockAmount == 0 && AllDone != null )
		{
			
			 CheckObjectsHaveStopped();
		}	
		
	}
	
	void CheckObjectsHaveStopped()
	{
		print("checking... ");
		Rigidbody[] GOS = FindObjectsOfType(typeof(Rigidbody)) as Rigidbody[];
	
			foreach (Rigidbody GO in GOS) 
			{
				StartCoroutine ( CheckMoving( GO ) );
				print(GO.name + " " + GO.velocity.magnitude);
			}
	
		
		//AllDone( true );
	}
	
	IEnumerator CheckMoving ( Rigidbody GO )
	{
		do
		{
			print(GO.name + " " + GO.velocity.magnitude );
		} 
		while (GO.velocity.magnitude > 0.1 );
			
		yield return null;
	}
	
	void Update()
	{
		CheckObjectsHaveStopped();	
	}
}

If you want a coroutine that will end only when all the rigidbodies have stopped it sould be something like this:

void Start()
{
   StartCoroutine(CheckObjectsHaveStopped());
}

IEnumerator CheckObjectsHaveStopped()
{
    print("checking... ");
    Rigidbody[] GOS = FindObjectsOfType(typeof(Rigidbody)) as Rigidbody[];
    bool allSleeping = false;
    
    while(!allSleeping)
    {
       allSleeping = true;

       foreach (Rigidbody GO in GOS) 
       {
          if(!GO.IsSleeping())
          {
             allSleeping = false;
             yield return null;
             break;
          }
       }
    
    }
    print("All objects sleeping");
    //Do something else

}

Some observations: I’m starting the coroutine in Start, but you could start in another place. Just make sure to start it once. Another point is that I’m checking if the object IsSleeping instead of velocity.magnitude <= 0.1f, but you could change it back.

You don’t need the while loop and the break. The while loop will end when you do return.
` foreach (Rigidbody GO in GOS)
{
if(!GO.IsSleeping())
{
allSleeping = false;
yield return null;

     }
}

`