Check if object is visible to Main Camera

I am trying to find ways to optimize a high poly CAD file imported as FBX. For reasons I won’t go into I am unable to reduce the poly count (roughly 4 million tris, verts!!).

As an alternative I want to explore ways to dynamically hide parts of the imported mesh NOT currently seen by the Main camera. ie I am NOT talking about frustrum culling, which works by default, rather I want to turn an object ‘OFF’ ie Setactive(false), if that object is hidden or occluded by another object.

Is this possible? Or would the cost of checking visibility to the Main Camera nullify any performance gains thru a reduced Poly count?

After some googling I wonder if Raycasting is what I need

If the following script was put on the Main camera and I substitute ‘player’ with the object I am checking>

var hit : RaycastHit;
var rayDirection = player.position - transform.position;
if (Physics.Raycast (transform.position, rayDirection, hit)) {
if (hit.transform == player) {
// enemy can see the player!
} else {
// there is something obstructing the view
}
}

Not sure if you’ve seen it but there are a few bit of information on this subject in these old threads:

Maybe they can help you out

Thanks will check those out. Also figured a more efficient way to find the ‘root’ material object of my FBX mesh is to tag them, and then in my Start method populate an Array or list with these objects using FindGameObjectsWithTag

There are a couple of ways. You can implement “OnBecameVisible” and “OnBecameInvisible”:

If you want more exact control, you can use a CullingGroup:

2 Likes

Unfortunately my mesh is Dynamic ao AFAIK cannot use Occlusion culling.
OnBecameInvisible

is interesting but confusing.
After reading this thread Are OnBecameVisible and OnBecameInvisible named poorly? - Unity Engine - Unity Discussions
I assume that OnBecameInvisible ONLY gets called in the editor if your Scene view tab is closed AND the gameObject in question is leaving the Main Camera’s frustrum.
So just frustrum culling which is enabled by default anyways…

But if I understand correctly, it SHOULD work as anticipated if you are deploying to iOS??

OnBecameVisible and OnBecameInvisible work in editor too, they just check for the scene view camera as well as your “normal” cameras in hierarchy.

So in editor, for example, OnBecameInvisible is called when the object is not visible neither in scene view, nor by any of your cameras

2 Likes