Print out the closest object in scene

Hi guys, i’m studding Unity 2d and i’m having a problem to print out the closest object position. Here is the scenario:

I have two kind of objects, workers and resources, and i need that my worker know which is the closest resource object.

I put some code in worker.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Worker : MonoBehaviour
{
    
    Transform closestResource = null;
    List<Transform> resourceListTransform = new List<Transform>();

    void Update()
    {
        if (closestResource == null)
        {
            GetListOfTransformInResources();
            GetClosestResource();
            Debug.Log(closestResource.position);
        }
    }

    void GetListOfTransformInResources()
    {
        var resources = FindObjectsOfType<Resource>();
        foreach (Resource r in resources)
        {
            resourceListTransform.Add(r.transform);
        }
    }

    void GetClosestResource()
    {
        Transform tMin = null;
        float minDist = Mathf.Infinity;

        Vector2 currentPos = transform.position;

        foreach (Transform t in resourceListTransform)
        {
            float dist = Vector2.Distance(t.position, currentPos);
            if (dist < minDist)
            {
                tMin = t;
                minDist = dist;
            }
        }

        closestResource = tMin;
    }
}

And i’m getting these prints:

Worker is printing all resources that i have in scene (and i have two resources object in scene) not just the closest.

What i’m doing wrong?

Thanks

Hi David,

Store the first resource in a variable. Then compare the distance between the stored variable and the worker to the distance between the next resource and the worker. Then do nothing or store the next resource in the variable. And so on.

The code would suggest that you have a 2nd game object in the scene that also has the Worker component/script on it.

Can you also debug.log the game object name and the count of Worker objects to help confirm?