- Home /
Efficiently detecting distance in children objects
is there a way for a parent object to efficiently detect if a target object gets within a certain distance from any of his children objects?
Answer by duck · Apr 30, 2010 at 07:11 AM
Something like this should be fine, and it's optimised to use square distance values, to avoid the square root involved in computing the distance between two objects.
var threshold : float; private var thresholdSqr : float;
function Start() { // pre calculate square threshold, for use later in optimised distance check thresholdSqr = threshold * threshold; }
function CheckTargetRange() : boolean { for (var child : Transform in transform) { var distanceSqr = (child.position - transform.position).sqrMagnitude; if (distanceSqr < thresholdSqr) { return true; } } return false; }
Congratulations on being Awesome! and if I just wanted to check 1 of it's children, would I just do a transform.find("childName")?
Your answer
![](https://koobas.hobune.stream/wayback/20220612201740im_/https://answers.unity.com/themes/thub/images/avi.jpg)