- Home /
How to know when a object is in the viewport?
I know onbecamevisible exists, but because of the way it works it's not really correct.
Visible to the camera doesn't mean visible to the player because it becomes visible offscreen because of shadows and whatnot.
What I need to know is when a mesh is actually in the game's viewport.
Any ideas?
Answer by LCStark · Sep 29, 2018 at 10:03 AM
I needed the same thing to display unit UI only when the unit was visible to the camera. This is what worked for me:
bool visible = GeometryUtility.TestPlanesAABB(camera.planes, renderer.bounds);
camera
is a reference to my CameraController
object, in which I've calculated the camera's planes using GeometryUtility.CalculateFrustumPlanes
and stored them in Plane[] planes
, renderer
is a cached Renderer
object.
Yup that works thx.
Another note that might be helpful, if you didn't do it already, is providing the array yourself to prevent GC allocations.
GeometryUtility.CalculateFrustumPlanes(camera, customArray);
No problem! Yeah, I've done that as well. $$anonymous$$y camera controller creates a Plane[6]
array in its Start
method and uses it in Update
to get the current planes via CalculateFrustumPlanes
. Re-allocating that every frame wouldn't be very efficient. :)
$$anonymous$$ I found another solution that might be a bit simpler :P
Camera.main.WorldToViewportPoint(transform.position)
If not between 0-1, it's offscreen
Your answer
Follow this Question
Related Questions
Problem is "renderer.isVisible" 3 Answers
Unable to see proper view in viewPort 0 Answers
GameObject and Camera visibility 1 Answer
Problems with the visibility of an animated object 1 Answer
Crosshair Not Parallel To camera 1 Answer