- Home /
Object.Find distance?
When you are using GameObject.Find, is there a way to only find objects that are within a certain distance from the object that has the script?
var hand : GameObject;
// This will return the game object named Hand in the scene.
hand = GameObject.Find("Hand");
For example, if there is an object that is more than 10 units away, the script will just ignore it?
Answer by Peter G · Feb 03, 2011 at 10:50 PM
Yes, but it requires you do some iterating. It would probably be faster to use a trigger.
var hand : Transform; var scriptObjs : YourScript[];
var nearDist : float = 10.0;
function Start () { hand = GameObject.Find("Hand").transform;
scriptObjs = FindObjectsOfType(YourScript) as YourScript[];
//AFIK there is no generic implementation of FindObjectsOfType().
}
function Update () { for(var possibleObj : YourScript in scriptObjs) { if(Vector3.Distance(hand.position, possibleObj.transform.position) < nearDist) { //Do whatever you need to the object is closer than nearDist; } } }
Im sorry but I am a little confused. If I want to find the closest object with the tag "block" what would I do to your script?
Also, would this work with two objects (I want to find the closest one that is more than 1 unit away and the closest one that is less than -1 unit away)?
that is a little more complicated, you could do it though. You need to find the closest object with a dot product ((objPos - transform.position).normalized, transform.forward) greater than 0 and the other less than 0. I'll give an example later if I get a chance.
Your answer