Answer the question
In order to leave comments, you need to log in
Unity - how to find the 3 closest objects from an array?
So I wrote such a code, but firstly it is resource-intensive, and secondly, it finds the distance only to the nearest object.
Added objects to the array:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Rasstoyanie : MonoBehaviour
{
GameObject[] enemy;
GameObject player;
public string nearest;
private void Start()
{
enemy = GameObject.FindGameObjectsWithTag("Enemy");
}
}
GameObject Find()
{
float dist = Mathf.Infinity;
Vector3 position = transform.position;
foreach(GameObject go in enemy)
{
Vector3 diff = go.transform.position;
float currdist = diff.sqrMagnitude;
if(currdist < dist)
{
player = go;
dist = currdist;
}
}
return player;
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question