- Home /
Find Closest GameObject in a players vicinity
hey I am going to make a madeup example that explains my "problem"
Im making a game thats about managing a Lumberjack RPG :) The Lumberjack has a Skill called "treefinding" wich makes him able to find the closest tree automatically. Since there is Thousands of trees in the game, I do not want to Lumberjack to look through all trees and then find the closest, I want him to look within a vicinity of where he is standing, if he cant find anything within that, he will make the area in wich he is looking bigger.
Is there any easy way to find objects within a range, so I dont have to go through all trees to find the closest one? I am thinking in terms of using "FindGameObjectsWithTag" within the area where I want to look? If I did not make sence, please let me know
Thanks for your time
Answer by · Sep 23, 2010 at 09:05 AM
You can use Physics.OverlapSphere to "return an array with all colliders touching or inside the sphere". You can also pass in a LayerMask, so it will only return trees (if you set it up to do so). You would then iterate through that array to find the nearest GameObject.
If you have trouble with any particular part of that code, post what you've got and I'll try to help out. :)
Your answer
![](https://koobas.hobune.stream/wayback/20220613073713im_/https://answers.unity.com/themes/thub/images/avi.jpg)