Oct
31
2018

Find Nearby Objects using CullingGroup

Saw this tip at #UniteKL18, fast way to get nearby objects using CullingGroup!
(main image with 5000 gameobjects, searching objects within 3m radius)

example source code:
https://github.com/UnityCommunity/UnityLibrary/blob/master/Assets/Scripts/Docs/UnityEngine/CullingGroupExample.cs

my example project:
https://github.com/unitycoder/GetNearestObjectsWithCullingGroup

Some notes on that:
– You need to have MainCamera in the scene (as it uses that in “cullGroup.targetCamera = Camera.main;”)
– You need to set proper bounds for your objects, i’m currently doing that inside that for-loop (see b.position=.. and b.radius=..)
– i’m using array of Renderers to keep track of spawned objects (just to make it easy to change color without GetComponent<Renderer>), but you might want to use List, so that can add/remove objects there easily.
– I’m spawning objects on 2D circle, but this would work in 3D too

TODO
– Compare speed with OnTriggerEnter, Physics.OverlapSphere, BruteForce LINQ distances query, KD/QuadTree
– Test how this works with moving objects? (to get closest enemies for player..)
– Test how to get closests objects to 2 points? (probably cannot easily?)

Can also check which objects are outside camera view:


3 Comments + Add Comment

  • I tested with OnTrigger and also for moving objects. The performance is almost 5 times better with CullingGroup

  • Any update on this? Ive been using CullingGroup stuff for basic culling/LOD but this use case really interests me!

    I’ve looked at K-D trees too – but this seems like it might be faster out of the box?

  • UnityEngine.CullingGroup API for everyone
    https://github.com/mackysoft/Vision

Leave a comment

Connect

Twitter View LinkedIn profile Youtube Github Join Discord Twitch Instagram BlueSky

UnityLauncherPro

Get UnityLauncherPRO and work faster with Unity Projects!
*free unity hub alternative

@unitycoder_com

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.