Find the nearest enemy center of the screen

Help please I have been madly searching for an answer to accomplish the following:

1 - Find all GameObjects with given Tag and save it in a variable array.
2 - Select the object closest to the center of the screen and save your position in a variable.

I found this code but this looks the closest object to the player and not global coordinates of the screen.

using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
    GameObject FindClosestEnemy() {
        GameObject[] gos;
        gos = GameObject.FindGameObjectsWithTag("Enemy");
        GameObject closest;
        float distance = Mathf.Infinity;
        Vector3 position = transform.position;
        foreach (GameObject go in gos) {
            Vector3 diff = go.transform.position - position;
            float curDistance = diff.sqrMagnitude;
            if (curDistance < distance) {
                closest = go;
                distance = curDistance;
            }
        }
        return closest;
    }
    void Example() {
        print(FindClosestEnemy().name);
    }
}

I can not convert the position of all enemies to calculate 2d which is closer to the center.

Although give me a clue

You can use the cameras WorldToViewportPoint() method to find an objects position in the view port. It returns a Vector3 with values ranging from (0, 0, frustum start) to (1, 1, frustum end). Center of the screen therefore would have the x and y components of the vector be 0.5.

You could subtract (0.5,0.5,0) from that vector and set z to zero and see which one of the game objects vector has the lowest magnitude.

please give me an example of how to do it.

do you really need an example of looping over a collection, getting their positions, transform to screen space, and comparing the distance from the mid-screen?

Try to write it, if you fail, come back and show us and we can point you in the right direction. But please, at least try a little bit.

#pragma strict

function Start () {

}

function Update () {
	if(Input.GetKeyDown(KeyCode.E)) Debug.Log(GetClosest("Player"));
}

function GetClosest(tagName:String){
	var objects:GameObject[] = GameObject.FindGameObjectsWithTag(tagName);

	var closest:GameObject;
	var dot:float = -2;
	for(var obj : GameObject in objects){
		// store the Dot compared to the camera's forward position (or where the object is locally in the camera's space)
		// Very important that the point is normalized.
		var localPoint : Vector3 = Camera.main.transform.InverseTransformPoint(obj.transform.position).normalized;
		var forward : Vector3 = Vector3.forward;
		var test:float = Vector3.Dot(localPoint, forward);
		if(test > dot){
			dot = test;
			closest = obj;
		}
	}

@bigmisterb Thanks for your attention

I do not understand exactly what this code does but I need is a variable returns the closest object to the center screen. if use debug.log not print the name of the nearest enemy.

The code throws this error:
IndexOutOfRangeException: Array index is out of range
¿In that variable is saved the nearest enemy?

Using Code tags would do better than quote tags.

I rewrote it to match what you are trying. I also set it to accept a tagName and returned a GameObject.

what does the code do?

It gathers all game objects with a certain tag. “Enemy”
It then goes through each one.
It uses the objects position in the camera’s space (InverseTransformPoint converts a “global” point to a “local” point)
It uses Vector3.forward compared to that point
It uses Vector3.Dot() to check the forward point to the local point. (Vector3.Dot)
It compares the dot to the last dot we recieved. If that number is higher (closer to 1) then we store the object for later use.

I’ve tried all ways and I can not get
Thank you very much for the explanation, one thing ultiam, which tells me this error? which means?
IndexOutOfRangeException: Array index is out of range
I think you’re trying to access an array position that is not within the range initialized.
I say that in no time you book size to variable objects.

If you can write him a function to return the 3D position and name of the nearest enemy and no more annoying.

If you have not re-pulled the code… the problem is:

objects
Should have been
objects[index]

:smile:thanks,thanks,thanks,thanks,thanks * 1,000,000.00
Problem solved, sorry for bothering both :wink:

#pragma strict
      
function Update () {

   if (Input.GetButton ("E")){     

    var objects:GameObject[] = GameObject.FindGameObjectsWithTag("Objetivo");
    var closest:GameObject;
    var dot:float = -2;

        for(var obj : GameObject in objects){
        // store the Dot compared to the camera's forward position (or where the object is locally in the camera's space)
        // Very important that the point is normalized.

        var localPoint : Vector3 = Camera.main.transform.InverseTransformPoint(obj.transform.position).normalized;
        var forward : Vector3 = Vector3.forward;
        var test:float = Vector3.Dot(localPoint, forward);
        if(test > dot){
            dot = test;
            closest = obj;
        
        print (obj);
        }
    }    
  }
}