Visibility of objects

Hello. How to define visibility of object. For example as on a screen the cube behind a green wall has to be defined as invisible. Something such is used in the Occlusion Culling technology.
alt text

With the information in your further comments, it sounds like you want OnWillRenderObject: Unity - Scripting API: MonoBehaviour.OnWillRenderObject()

Call that function in a script attached to the cube and it will tell you which cameras will render it. If the function doesn’t get called for a particular camera, the object is “invisible” to that camera.

tanoshimi answer helped me. You cannot made it with OnBecameVisible and OnBecameInvisible, because they get called only when the objects change visibility, that they are many or one camera having the object in view do not change anything. OnWillRenderObject are only called on gameobject having a renderer attached. (childrens do not counts).
I tested it with occlusion culling (don’t forget you have to bake it in Unity in the occlusion culling panel) and it work. In case you are moving the MeshRenderer you have a checkbox ‘Dynamic Occluded’ that should be setted to true (only beginning from unity 2017.2, on version bellow it is by default true).

This bellow is WIP, but should help understanding:

        private List<Camera> cameraSeeingMe;
        private Array<Camera> cameraSeeingMeBuffer;

        private void OnWillRenderObject() {
            // OnWillRenderObject is called even when editor pause, better avoid duplicate
            if (!isRenderingMe.Exists((e)=> e == Camera.current))
                cameraSeeingMe.Add(Camera.current);
        }
        
        private void Update() {
            cameraSeeingMeBuffer = cameraSeeingMe.ToArray();
            cameraSeeingMe.Clear()
        }
        
        public bool isSeenBy(Camera cam) {
            foreach (var otherCam in cameraSeeingMe) {
                if (cam == otherCam ) {
                    return true;
                }
            }
            return false;
        }

You can add a gizmo to see what happen. We use the buffer because OnDrawGizmos get called immediately after OnWillRenderObject, and not after Update. (without buffer some gizmos won’t be draw on some camera)

        private void OnDrawGizmos() {
            Gizmos.color = Color.yellow;
            foreach (var cam in cameraSeeingMeBuffer) {
                Gizmos.DrawLine(transform.position, cam.transform.position);
            }
        }

[Edit]: Few corrections after more testing.

You could make a bool called Visible or something and then use a raycast and see if anything is in the way. If it is, Visible = false; Else Visible = true;