How do I only get bounds of the visible parts of an object?

I need to track what percent of the screen the enemy is taking up. The solution I think will work is to get the renderer bounds of the enemy and make a rect around it in screen space, then compare the sizes. I made the rect as a GUI box to test. My problem right now is that the bounds of the object are displaying the entire object even if only part is visible.

This gets the dimensions correctly

But this should have the gui rect smaller than it is displaying because it is obstructed by another object

If there is a better solution to what I am trying to do then I’d also be open to that.

@MrSnoozable

This is a fun one, because the object, when it is rendered, is technically visible. Later on, another object is rendered on top of it. Your GUI box is giving you a pretty good idea of whether it’s ‘on screen’ or not.

To get more accurate that that, one way is to analyze the rendered image after it’s been created. Here is my suggestion on steps to do that:

  1. Use the Scriptable Render Pipeline so that you can easily script your render passes
  2. Create a special render pass that runs before your main render, rendering at a much lower resolution. Like 160x100. Maybe smaller than that. Tiny.
  3. In this pass, you render your object in question with an UnLit white material, and everything else with an Unlit Black material.
  4. You should have a reference to the rendered image now.
  5. Use more standard pixel processing techniques to get the bounding box of the white pixels in that image.

You can continue on to render your scene as normal now.

I can acknowledge this is a pretty high level explanation - and that there are certainly other ways to do this. Has this been sufficiently outlined for you?

Helpful References:

Scriptable Render Pipeline: What You Need To Know

Scriptable Render Pipeline Overview

In addendum – once it’s working, you can tweak the image size and your pixel search algorithm to get faster and better results. Even better, once you have this working you can use it for all sorts of other effects and features.