nearest game object infront of camera

I'v used this code to find the nearest game object with a certain Tag.

I'm wanting to get the neareset object but infront of the camera (not behind me)

Not sure were to start to be honest

any suggestions

function GetNearestTaggedObject() : Transform {

    var nearestDistanceSqr = Mathf.Infinity;
    var taggedGameObjects = GameObject.FindGameObjectsWithTag(searchTag);

    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 - targetplayer.transform.position).sqrMagnitude;

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

    return nearestObj; }

You can get the angle between your looking direction (`transform.forward`) and the direction to your object (`obj.position - transform.position`) by using Vector3.Angle:

var targetDir = target.position - transform.position;
angleBetween = Vector3.Angle (transform.forward, targetDir);

You can then use the `angleBetween` - if it is between -90 and 90, the object is in front of you. You can even change this "field of view" as you like.

I'd just add this at the top of the loop:

if (obj.renderer == null || !obj.renderer.isVisible) continue;

It'll skip any non visible object (which means it'll only find objects with renderers), which may or may not be what you want