Following script illustrates how to receive events according to visibility to a set camera.
This script uses several performance heavy methods for brevity.
using UnityEngine;
using System.Linq;
public class CullingGroupCameraBehaviour : MonoBehaviour
{
CullingGroup localCullingGroup;
MeshRenderer[] meshRenderers;
void OnEnable()
{
localCullingGroup = new CullingGroup();
meshRenderers = FindObjectsOfType<MeshRenderer>()
.Where((MeshRenderer m) => m.gameObject != this.gameObject)
.ToArray();
BoundingSphere[] cullingPoints = new BoundingSphere[meshRenderers.Length];
Transform[] meshTransforms = new Transform[meshRenderers.Length];
for (var i = 0; i < meshRenderers.Length; i++)
{
meshTransforms[i] = meshRenderers[i].GetComponent<Transform>();
cullingPoints[i].position = meshTransforms[i].position;
cullingPoints[i].radius = 4f;
}
localCullingGroup.onStateChanged = CullingEvent;
localCullingGroup.SetBoundingSpheres(cullingPoints);
localCullingGroup.targetCamera = Camera.main;
}
void CullingEvent(CullingGroupEvent sphere)
{
meshRenderers[sphere.index].material.color = sphere.isVisible ? Color.red : Color.white;
}
void OnDisable()
{
localCullingGroup.Dispose();
}
}
Add the script to scene and hit Play. All geometry in scene will change color based on their visibility.
Similar effect can be achieved using the
MonoBehaviour.OnBecameVisible()
method if the object has aMeshRenderer
component. Use CulingGroups when you need to cull empty GameObjects,Vector3
coordinates, or when you want a centralised method of tracking object visibilities.