W
W
Wadim_wadim20002020-05-15 10:05:35
C++ / C#
Wadim_wadim2000, 2020-05-15 10:05:35

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");
    }
}

and in this part you need to find instead of 1 object, the 3 closest ones:
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;  
    }

can you correct and suggest how to find the next 3 objects? Just the first time I encountered arrays.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Kot Kotov, 2020-05-15
@kot123123

It is necessary to make a parser from for. It will check each object in the array and then you need to take data from each object.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question