Checking how many GameObjects are with a radius

Hello there,

I am just experimenting around with Unity and all and I was trying to find a way to detect how many objects are there in a pre-defined radius of an object. This is my script so far. However, there this problem whenever I try to duplicate an object tagged “Cube” while running the game, it doesn’t seem to detect properly.

 #pragma strict
    
    var threshold: float;
    var inRange: boolean;
    var totalCount: int;
    
    function Update()
    {
    checkDistance();
    }
    
    function checkDistance()
    {
    var detectedObjects = GameObject.FindGameObjectsWithTag("Cube");
    totalCount = 0;
    
    	for (var detectedObject in detectedObjects)
    	{
    		if (Vector3.Distance(detectedObject.transform.position, transform.position) < threshold)
    		{
    			inRange = true;
    			totalCount++;
    		}
    		
    		else
    		{
    			inRange = false;
    			
    			if (totalCount != 0)
    			{
    			totalCount--;
    			}
    		}
    	}	
    }

http://docs.unity3d.com/Documentation/ScriptReference/Physics.OverlapSphere.html

This will detect objects with colliders within a given radius. It can also be used with a layermask to be selective.

static function
OverlapSphere(position: Vector3,
radius: float): Collider;

static function
OverlapSphere(position: Vector3,
radius: float, layerMask: int):
Collider;