I think that the best approach is to keep a list of GameObjects ordered by the distance from the player. You’ll need to order the list every update ( or less if you don’t need accurate results ). Then you can solve all the “distance related problems” just by accessing the first elements of the list.
To find objects close to your player, you could run a list using Triggers - objects are added to the “within bounds” list OnTriggerEnter() and removed OnTriggerExit().
Using this list - you could minimize the number of objects you need to compare Vector3.Distance() to in order to find the closest obstacle to the player.
As for game objects visible on the screen…
My immediate theory would be to create an abstract base class that overrides OnBecameVisible() and OnBecameInvisible() - using these calls per-object to subscribe to and unsubscribe from a “visible object” list.
Physics.OverlapSphere returns an array of colliders in a sphere. but if your gameobjects dont have a collider this doesnt help you. but if the objects in vicinity are much less than all objects in scene this may be faster than going though all objects yourself.
if you need to check through a list of all objects just make a simple sphere-sphere test with the squared distance (avoid taking the root from every distance at all cost). and also just execute this search every second or something.
As regard the Physics.OverlapSphere would be the best method ready to use but the problem is that I would like to know within a square area and not a sphere.
It seems that the best solution for the performance thing would be using the OnTriggerEnter() method to create a list of objects within a certain distance and then using a Vector3.Distance method to compare the distances from the player.
Do you think there could be any optimization on this procedure?
Then simply use the sphere method for a preselection wich gives you all objects within the bounding sphere of the square/cube you desire and apply the additional criteria (square) you need.
Or you use a cube collider of the size instead.
Don’t use sphere overlap, its costly. Instead attach a trigger cube to the player, which will return all things that enter it, leave it, and remain inside it. it is even recommended in unity docs for speed purposes.
i dont know the performance of the unity functions and usually i dont care about. i just wanted to add an option for anfex to choose from. sometimes the development comfort is more important than the runtime behavior.
so its good that you clarified the performance but it is not bad that i suggested it imo.