Most efficient way of detecting closest objects around?
I'm considering how to detect the closest object around my hero. This is gonna be called for every frame so I really need the most efficient way.
Should I do a For loop of my array of objects and calculate the distance of each object to my hero and choose the smallest value?
Or should I use other means such as raycasts?
I'm targeting mobile so every bits of CPU saving helps.
Answer by Pangamini · Sep 09, 2015 at 08:18 AM
Physics engine inside unity keeps colliders in some structure that makes if fast to query objects in an area (99% sure it's an octree). So when you are using Physics.OverlapSphere, it should be optimized and fast. This will only work with colliders though, not with any GO / Transform (since the octree is part of physics engine) and if you plan to move them around, you'd better have a kinematic rigidbody there as well.
If you need / want, you can implement your own octree and fill it with your objects. This can be handy if you want to have multiple parallel "worlds" populated with objects where you can search, or you simply don't want to use colliders and physics and waste some unity layers for filtering them out.
Also don't forget that objects returned by OverlapSphere are deter$$anonymous$$ed using collider and sphere's bounding boxes, so it's just a rough list. It will contain all objects inside the sphere, but may contain some more, so you should do another, more expensive pass on the returned list
Hi there, thanks for your response. None of the objects around my hero have rigidbodies. I want to keep them free of physics to have complete control over them. Can I just add a trigger collider to my objects and do "collider.gameobject.transform.position"?
Answer by Eno-Khaon · Sep 09, 2015 at 04:26 AM
If you're looking for pure efficiency, you might want to consider using a trigger area collider sphere around your character.
As a script on that, you would use OnTriggerEnter() to compile a running List<> of objects as your character gets near them and then OnTriggerExit() to clear them out of the list.
Then, you'll only need to check whichever objects are contained within a close range of you to determine which is closest after that.
If you have extremely few objects in the scene or they're all generally going to be very, very far away (and you still want to know which is closest), then you might consider alternative methods instead.
Edit: Fixed formatting for "List<>"
Your answer
Follow this Question
Related Questions
Is instantiating empty gameObjects heavy on the CPU? ( Object pooling) 1 Answer
Is using multiple cameras, culling masks, and layers expensive on mobile? 1 Answer
Performance issue new project vs everything deleted in old project 0 Answers
How to optimise image effects on Android? 1 Answer
Multi-core PCs and performance. 0 Answers