Question by
Noxury · Nov 15, 2015 at 04:48 PM ·
gameobjectfindnearest
Get nearest GameObject
Hello,
I have read several posts on this topic, but this has not worked for me. Here is my approach:
var target : GameObject;
var homing: boolean;
function Start () {
if(Rigidbody){
GetComponent.<Rigidbody>().AddRelativeForce(0,0,10);
}
if(homing){
FindClosest();
}
}
function FindClosest() : GameObject {
var gos : GameObject[];
gos = GameObject.FindGameObjectsWithTag("Dynamic");
var distance = Mathf.Infinity;
var position = transform.position;
// Iterate through them and find the closest one
for (var go : GameObject in gos){
var diff = (go.transform.position - position);
var curDistance = diff.sqrMagnitude;
if (curDistance < distance){
closest = go;
target = closest;
distance = curDistance;
}
}
return closest;
}
function Update () {
if(homing && target != null){
transform.LookAt(target.transform);
}
}
The target variable is always empty.
Comment
Answer by ZeraTFK · Nov 15, 2015 at 05:15 PM
Did you find the gameobjects with GameObject.FindGameObjectsWithTag("Dynamic"); ?
Try
Vector3.Distance(firstObject, secondObject) to get the distance and change var distance = Mathf.Infinity; to var distance = -1
function FindClosest() : GameObject {
var gos : GameObject[];
gos = GameObject.FindGameObjectsWithTag("Dynamic");
var distance = -1;
var position = transform.position;
// Iterate through them and find the closest one
for (var go : GameObject in gos){
var curDistance = Vector3.Distance(go.transform.position, position);
if (curDistance < distance || distance == -1){
closest = go;
target = closest;
distance = curDistance;
}
}
return closest;
}
Your answer
Follow this Question
Related Questions
How Can I assign a gameobject via script? 0 Answers
How can I find object ? 2 Answers
Why does GameObject.Find() work in ones and not in others? 1 Answer
setting a variable to a GameObject that has a certain RGB value??? please help 0 Answers
How can we be notified the moment an object is instanced in the scene ? 3 Answers