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--;
}
}
}
}