Search Unity

Question How to check for the closest game object to player

Discussion in 'Scripting' started by S4MA3L, Jul 1, 2020.

  1. S4MA3L

    S4MA3L

    Joined:
    Apr 17, 2020
    Posts:
    38
    I was wondering if there is an efficient method to find the closest object to the player from the scene in unity during runtime. I am hoping to run a function only when the player character is at a certain distance from the closest game object. (2d game)
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,909
    Assuming your player has a rigidbody component, make a child GameObject of your player and attach a trigger collider to it. Then attach a script to the player that listens for OnTriggerEnter.
     
  3. S4MA3L

    S4MA3L

    Joined:
    Apr 17, 2020
    Posts:
    38
    Thanks a lot PraetorBlue.
     
    Last edited: Jul 1, 2020
  4. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,909
    Why do you need to know the closest GameObject? OnTriggerEnter will tell you which object has entered the trigger zone.
     
  5. Vryken

    Vryken

    Joined:
    Jan 23, 2018
    Posts:
    2,106
    Assuming you have a collection of GameObjects within a certain radius from the player:
    Code (CSharp):
    1. GameObject[] nearbyObjects;
    You can get the distance of each one from your player by looping through and subtracting their positions from your player's position, then using the value of the returned
    sqrMagnitude
    . Keep a cached variable of the current closest distance while looping through the GameObjects and update it if the next object's distance is smaller than the cached variable.
    Something like this:
    Code (CSharp):
    1. GameObject GetNearestObject(GameObject sourceObject, GameObject[] nearbyObjects) {
    2.    GameObject nearestObject = null;
    3.    float nearestDistance = float.MaxValue;
    4.  
    5.    for(int i = 0; i < nearbyObjects.Length; i++) {
    6.       float distance = (nearbyObjects[i].transform.position - sourceObject.transform.position).sqrMagnitude;
    7.  
    8.       if(distance < nearestDistance) {
    9.          nearestObject = nearbyObjects[i];
    10.          nearestDistance = distance;
    11.       }
    12.    }
    13.  
    14.    return nearestObject;
    15. }
    How you get the collection of nearby GameObjects is up to you. You can use the trigger collider method above, or a physics overlap-sphere call, or have a preset cached array of objects to compare, etc.
     
    EpicGamerEpic, aaron4202 and psykick1 like this.
  6. S4MA3L

    S4MA3L

    Joined:
    Apr 17, 2020
    Posts:
    38
    I want my player to enter a gravitational field of another GameObject only when it is at a fixed distance from the player. The trigger collider might work well for this I think. I am looking to find the closest GameObject and assign that specific game object to a script.