Calling GameObject's transform from list

Hello! I am trying to call a target from a list. I am trying to reference the transform.position for the gameObject I am calling (closestPlayer) so I can “MoveTowards” it. How do I do this? I’ve been looking at this yesterday and today getting addingly smarter (and frustrated), but I can’t seem to get it to work. Everything else works fine, though! :slight_smile:
Relevant code:

public class EnemyAI : MonoBehaviour {

	private GameObject closestPlayer;

	public float speed;
	public float maxDistance;

	public GameObject FindClosestPlayer() {
		GameObject[] gos;

		gos = GameObject.FindGameObjectsWithTag("Player");

		maxDistance = 300f;
		Vector3 position = transform.position;
		foreach (GameObject currentPlayer in gos) {
			Vector3 diff = currentPlayer.transform.position - position;
			float curDistance = diff.sqrMagnitude;

			if (curDistance < maxDistance) {
				closestPlayer = currentPlayer;
				maxDistance = curDistance;
		return closestPlayer;

	void Update () {
		GameObject closestPlayer = FindClosestPlayer();
//		transform.position = Vector2.MoveTowards(the closestPlayer <--

As you can see for the last line of code, I want to reference the “closestPlayer” correctly, so my EnemyAI can move towards it! I appreciate any help, thank you.

You could simply use


Its better to work with transforms directly if you are mostly interested in position. Change the return type of FindClosestPlayer to a transform. Then you could use