- Home /
Cast a ray only against "isvisible" objects
The unity documentation for raycasting says that a raycast "Casts a ray against all colliders in the scene."
I only need to raycast against the colliders of objects which have renderer.isVisible == true
. I'm thinking it would relieve a lot of strain on the CPU if you had a scene with a ton of colliders.
Does anyone with more unity know-how have any idea if this is possible?
Would I gain anything performance-wise if I had a script on each object (and say I have 1600 objects) which turned its collider on or off based on their own OnBecameVisible()
or OnWillRenderObject()
events?
Or would the only option be, implementing your own raycast/collision system which keeps track of isVisible objects on its own?
The physics engine is already pretty well optimized; it uses spatial partitioning to reduce the number of objects it needs to check at any given time. The documentation suggests a raycast is checked against "all" colliders, which is true in terms of results but not how it's calculated.
With that said, spatial partitioning is less effective when you have a very large number of colliders close together. Unless you're doing that, you probably don't need to worry about it.
If you're having a performance problem, you might consider reducing the number or distance of your raycasts, so that it has fewer colliders to check against.
Thanks rutter, that's kinda what I wanted to hear. So let's say I have a large cube of cubes. (each with a collider) And I am standing in its center. And I cast a bunch of rays in the direction the camera is viewing. Would uniy's spatial partitioning only fetch objects spatially located in front of the camera (because that's the direction of the ray)?
And one last concern: is the spatial partitioning based on the GO.transform.position? Because my "cubes" are procedurally generated, and even though the cube mesh, mesh bounds, and cube collider are in a certain (correct) point in space, the gameobject.transform.pos
is always at 0.0.0...
Raycast CPU consumption seems to be constant enough as far as I can tell. So it probably means it's working efficiently :P
Answer by WhoRainZone1 · Aug 13, 2014 at 01:11 AM
I'd suggest you using tags on your GameObjects, as you can create Layermasks to define which tag to ignore and which not. Then you just set the tag when making it visible/invisible.
Hope that does the trick, if not there are unfortunately no other way's to tell a raycast to not even bother checking that GameObject.
Cheers, WRZ