Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

how to get the closest object to the player?

Discussion in 'Scripting' started by xAmrxxxx, Aug 22, 2016.

  1. xAmrxxxx

    xAmrxxxx

    Joined:
    Jan 5, 2016
    Posts:
    56
    i have a couple of enemies and i want my to reference the closest one to the player position I can't think of a simple way to do it so help please?
     
  2. raycosantana

    raycosantana

    Joined:
    Dec 23, 2012
    Posts:
    319
    You can get the distance between two objects by using Vector3.Distance(), it takes two vector 3 variables, in this case the position of the player and the position of the enemy and it returns a float variable (the distance between the two objects), store the variable in a list and sort the list by the sortest distance.

    Vector3.Distance Ref
     
  3. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    for a "couple of enemies" you'll probably find its simplest to just iterate over all the enemies and check the distance to each (https://docs.unity3d.com/ScriptReference/Object.FindObjectsOfType.html will grab all instances of a component in the scene, i.e. the enemy script, if you haven't stored a list of them)

    with many more enemies you might consider an physics.overlapsphere check to pull off the ones nearest in the scene, before iterating over them to determine the closest.

    Or, either way you get the list, you can always sort the array/list by distance using a delegate or linq