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){
}

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.

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