# find the closest gameobject to the player.

hi I’ve got this code that find the closest object and out puts the information as a transform.

``````   function ScanForTarget() {
// this should be called less often, because it could be an expensive
// process if there are lots of objects to check against
target = GetNearestTaggedObject();

}

function GetNearestTaggedObject() : Transform {
// and finally the actual process for finding the nearest object:

var nearestDistanceSqr = Mathf.Infinity;
var taggedGameObjects = GameObject.FindGameObjectsWithTag("Enemy");
var nearestObj : Transform = null;

// loop through each tagged object, remembering nearest one found
for (var obj : GameObject in taggedGameObjects) {

var objectPos = obj.transform.position;
var distanceSqr = (objectPos - transform.position).sqrMagnitude;

if (distanceSqr < nearestDistanceSqr) {
nearestObj = obj.transform;
nearestDistanceSqr = distanceSqr;
}
}

return nearestObj;
}
``````

but I want some code that does the same as this but outputs its information as a gameobject so it can be read by this code.

``````	 var distance = Vector3.Distance( target.transform.position, transform.position);
if ( distance < distancefollow)
{
var delta = target.transform.position - transform.position;
delta.Normalize();
//Normalise prevents fluctuations in the velocity.

var moveSpeed = speed * Time.deltaTime;

transform.position = transform.position + (delta * moveSpeed);
//The Enemy chases the player until the player is out of range.
}
``````

Same code, just use it’s game object instead of transform.

target = GetNearestTaggedObject().gameObject;

wow it worked as simple as that,

just changed
target = GetNearestTaggedObject();
into
target = GetNearestTaggedObject().gameObject;

thnx

Why not return the type GameObject and change the line:

``````var nearestObj : Transform = null;
``````

to:

``````var nearestObj : GameObject = null;
``````

and the line:

``````nearestObj = obj.transform;
``````

to:

``````nearestObj = obj;
``````

and then:

``````return nearestObj;
``````

This will save the look up of Transform.gameObject at that step.