Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Get the closest target

Discussion in 'Navigation' started by Jarduk, Mar 16, 2015.

  1. Jarduk

    Jarduk

    Joined:
    Oct 30, 2014
    Posts:
    7
    Hello,
    I have 4 Players and the enemy should follow the closest one. This is my current script, but I don´t know how to fix it...
    the enemy follows the player with the 0 in the array all the time.


    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class Creeper : MonoBehaviour {
    5.  
    6.     private float[] distance_to_targets = new float[4];
    7.     private GameObject[] targets = new GameObject[4];
    8.     private int target_to_follow = 0;
    9.     private float shortest_distance = 0;
    10.  
    11.     private NavMeshPath path;
    12.  
    13.     NavMeshAgent agent;
    14.  
    15.  
    16.     // Use this for initialization
    17.     void Start ()
    18.     {
    19.         agent = GetComponent<NavMeshAgent>();
    20.         targets = GameObject.FindGameObjectsWithTag("Player");
    21.  
    22.     }
    23.    
    24.     // Update is called once per frame
    25.     void Update ()
    26.     {
    27.         for (int i = 0; i < targets.Length; i++)
    28.         {
    29.             agent.SetDestination(targets[i].transform.position);
    30.             distance_to_targets[i] = agent.remainingDistance;
    31.  
    32.             if (shortest_distance == 0)
    33.             {
    34.                 shortest_distance = distance_to_targets[i];
    35.             }
    36.  
    37.             else
    38.             {
    39.                 if (shortest_distance > distance_to_targets[i])
    40.                 {
    41.                     shortest_distance = distance_to_targets[i];
    42.                     target_to_follow = i;
    43.                     //Debug.Log(target_to_follow);
    44.                 }
    45.             }
    46.         }
    47.  
    48.         agent.SetDestination(targets[target_to_follow].transform.position);
    49.     }
    50. }
    51.  
     
  2. Jakob_Unity

    Jakob_Unity

    Joined:
    Dec 25, 2011
    Posts:
    269
    You cannot use setdestination to calculate the distance to the player in the same frame - as the path is calculated asynchronous. You can use agent.CalculatePath () to give you a path immediately - then calculate distance based on that (summing length of the segments between corners).

    You should move 'shortest_distance' to Update - not keep it as a member.
    Why not initialize it to a big number - that'll simplify your logic in the 'for' loop.

    Calling SetDestination/CalculatePath every frame can get expensive - you could set destination every X seconds or base the re-setting it on some distance moved.