I have a Mesh Renderer and a script assigned to a rotating sphere with a hole in it. The sphere has no specific or special place in hierarchy, its just next to the camera. The script part looks like this:
void OnBecameInvisible() {
Destroy(gameObject);
}
Problem is, that when I pass the sphere with my ball, even though the sphere is still half visible, it gets deleted. I have no other camera in the scene, and the one Im using is marked as the main camera.
Instead of using OnBecameInvisible
for culling objects you've passed, just check if it's sufficiently behind the camera in Update
:
Camera mainCam;
[SerializeField] float maxBehindDistance = 0.5f;
void Awake() { mainCam = Camera.main; }
void Update()
{
Vector3 relPos = mainCam.transform.InverseTransformPoint(transform.position);
if (relPos.z < -maxBehindDistance)
{
Destroy(gameObject);
}
}