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. Dismiss Notice

Search for Nearby GameObjects

Discussion in 'Editor & General Support' started by ibrews, Oct 9, 2014.

  1. ibrews

    ibrews

    Joined:
    Mar 21, 2013
    Posts:
    31
    I stumbled on a piece of sample Unity code that I would love to utilize, but I need to adjust it slightly. It searches through GameObjects with a certain tag, then returns the one that's closest. The only modification I want to make is to only search within a few feet of the player. If there isn't anything nearby, I don't want it to return anything. Here's the code (from here):

    Code (JavaScript):
    1. // Print the name of the closest enemy
    2.     print(FindClosestEnemy().name);
    3.    
    4.     // Find the name of the closest enemy
    5.     function FindClosestEnemy () : GameObject {
    6.         // Find all game objects with tag Enemy
    7.         var gos : GameObject[];
    8.         gos = GameObject.FindGameObjectsWithTag("Enemy");
    9.         var closest : GameObject;
    10.         var distance = Mathf.Infinity;
    11.         var position = transform.position;
    12.         // Iterate through them and find the closest one
    13.         for (var go : GameObject in gos)  {
    14.             var diff = (go.transform.position - position);
    15.             var curDistance = diff.sqrMagnitude;
    16.             if (curDistance < distance) {
    17.                 closest = go;
    18.                 distance = curDistance;
    19.             }
    20.         }
    21.         return closest;  
    22.     }
    Thank you for the help!
     
  2. makeshiftwings

    makeshiftwings

    Joined:
    May 28, 2011
    Posts:
    3,350
    You can change line 10 to "var distance = 5" or whatever value you want for the max distance from the player. This still loops through all the game objects but will return null if nothing is close enough. If you are trying to avoid looping through everything for performance reasons because you have a ton of objects, that's a little harder; you could put colliders on all the game objects and do Physics.SphereCast from the player to the max distance you want, and then only loop through the objects returned to find the closest.
     
  3. reentrant

    reentrant

    Joined:
    Oct 5, 2014
    Posts:
    59
    Wrong. It should be
    Code (CSharp):
    1. var distance : float = 5f;
    or
    Code (CSharp):
    1. var distance = 5f;
    or some arbitrary float

    You fail to mention the use of layer masks when doing sphere casts.