- Home /
Is there any way of finding closest object without a specified tag?
I am trying to make a enemy that follows the closest object in its range without a specific tag. i tried googling but all of the answers were just finding objects with tags. Can anyone please help?
Yes, but then it will follow everything, walls, floor, camera etc. And you would have to compare the distance to every object in scene. You could add all your followed objects to list and compare distance to them and pick the closest one.
Answer by Glurth · Feb 25, 2018 at 06:39 PM
This function will provide you a list of all collider objects within a given radius:
https://docs.unity3d.com/ScriptReference/Physics.OverlapSphere.html
Alas, the resultant list is NOT(I think) ordered in any particular way, so you would still need to loop through the results to find the closest object. Another limiting factor is that you must specify a radius: if no objects are found, expand the radius and try again. (but be careful with that; I suspect this is a fairly expensive function to call) Note: this solution requires that the GameObject to be found has a collider component attached to it.
Your answer
Follow this Question
Related Questions
Dynamic Laser Fence Scripting Problem 1 Answer
Find closest point of a sprite to GameObject 2D 1 Answer
How do i GET the the YRotation of an object? 4 Answers
Finding Closest Object is Destroy Both 1 Answer
How could I get a selection set of GameObject sharing a material or a script in Editor? 1 Answer