I am getting used to the unity environment and want to know if there are some functions or recommended ways in Unity to find the closest gameobject amoung a group of instantiated gameobjects.
If I was coding from scratch I would have an array in which I am storing a list of all gameobjects and their positions in the game and I could run through the array and calculate distance to find the closest object. And I would code a utility to manage the array and add gameobjects when they are created and remove them when they are destroyed. A lot of management code to be written.
In Unity is there some functionality where Unity would help me find/identify the closest gameobject from a group of objects that have been instantiated? It would cumbersome (and cpu costly) to maintain an array of gameobjects and to run through the array to find the closest.
Would like some advice on Unity functions or methods that would help identify the closest gameobject amoung a group of gameobjects flying around in the game.
I would guess the fastest way would be to have a function set to always output the distance of all game objects within “x” range. I say that because the engine is optimized for the 3D world, where as the arrays are mostly just identical to their C# counterpart. In terms of a built in function, unlikely. (You could feasibly do a collision field as well, though I think casting the vector distances would be less cpu intensive.
You wouldn’t need an array (though I’d hazard a guess it’s more efficient at this point.) All you would have to do is continually call the distances and store the lowest returning number, you’d have a lot of distance calculations being done, but not a lot of memory replacement. An array would likely see an equal, if not great need of resources to do the same thing.
If the things you’re checking have Colliders attached (and they probably should) you can use Physics.OverlapSphere() to get a list of all objects within a certain radius of your object. Then you could loop through those and get the one with the shortest distance to your object.
Another possible way would be to set up a co-routine script on objects to monitor which reported it’s distance periodically to a centralized GameObject. The closest two objects could then be stored such that if the closest one moved away in the future it’s a simple matter to swap to the second closest object until something else reported as closer.