- Home /
OnBecameVisible() not working as I'd hoped
Hey guys,
I need to know if a game object is visible on the screen. And I mean actually visible to the camera such that the player can see it, not behind a wall or whatever. I was hoping that OnBecameVisible() would do the trick for me.
But it turns out this message fires whenever the object enters the camera's view frustum, irregardless of depth culling. I put the object three rooms away behind several environment walls, there is no way it is visible to the camera (and yes, I made sure the editor camera was not pointing at the object).
I even tried making it static (along with the environment) and trying to use occlusion, but it's still firing that message inappropriately. I did turn off shadow casting/receiving on that object just in case, but that didn't help.
Any suggestions? Is there any way to know if an object is depth culled? If I could use some combination of OnBecameVisible() along with some sort of IsDepthCulled flag, that would seemingly do the trick, but I suspect Unity has no idea, since depth culling is done on the GPU, so I may be out of luck there.
I realize I could use a line cast (object transform to camera tranform) to look for collisions, but I think I will have too many of these objects for that to realistically work (potentially thousands of them). So I'm out of ideas, do I have any other options?
Unless you do use occlusion culling, your object will still be drawn (and overdrawn), thus .isVisible will be set.
Just out of curiosity: why would you want to know for lots of objects?
Good luck with a solution, however.
It's for a mapping system I'm working on.
Unfortunately, occlusion just isn't giving me reliable results. The message doesn't fire quite as often, but it still fires long before you could ever actually see the GO (and through walls). I guess that is probably due to the way the occlusion cells are set up.
I'm suspecting I'm going to have to line cast, which is a bummer. Unless there is maybe a shader solution? I don't know much about that aspect of shaders, can the pixel shader send a message back to the engine?
Answer by CostelloNicho · Nov 11, 2012 at 03:58 PM
The Renderer has an "IsVisible" flag -> Renderer.isVisible, which might work well for you in this situation.
Link: Unity Render.isVisible
Thanks for the answer, Syntinel, but unfortunately Render.IsVisible is giving me the exact same problem as OnBecameVisible() does. It doesn't respect depth culling, reporting as visible through environment walls.