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