Identify whether object is off screen or not

I have placed three game object in the scene.How to know whether the object is visible on the screen.Print a message if the object is not visible on the screen.

Take in mind, I'm not a big Unity user, however I can give you an answer, that works pretty much everywhere.

Prerequisits: you need to know the x and y FOV angle of the camera (you can calculate the x by taking the y FOV and multiplying it with the aspect ratio of the device), and the euler angles of the camera.

Create a vector, which points from the camera to the object you want to check against, then you can get the absolute angle of this vector with the following formula:

r := sqrt(x² + y² + z²)
yAngle := arctan(y / x)
xAngle := arccos(z / r)


Now, you know the absolute angles of the vector.

You need to divide the x and y angles of the camera from the x and y angles of the vector, this way you get the angles relative to the camera.

Here comes the trick: if the relative x and y angles are between the negative xFov and yFov and positove xFov and yFov (add some falloff to it of course), then it's inside the view of the camera.

However, this has some cons. The biggest and most obvious is that if your object is very big or is very close to the camera, then you can get false results. This can be solved by giving it a bigger falloff, but that won't work if you object likes to get close to the camera and then get far again, then this won't work either.

In cases like that, you should simply render it to a texture, and check if it is on it.

Unity has built-in methods to detect it. It's called the same way as OnTriggerEnter.

public class Invisibility : MonoBehaviour {
void OnBecameInvisible() {
Debug.Log("Im gone :(");
}
void OnBecameVisible() {
Debug.Log("Hi, Im back!");
}
}


Note: that if the object is visible on the Scene view OnBecameInvisible won't be called. Same way with OnBecameVisible - if it becomes visible on the Scene view. After building your game it shouldn't bother you, this only exists in the editor.

If you want to check if the gameobject is currently visible you can get his Renderer.isVisible (it returns true if the shadow is rendered).

If you want to detect via bounding box falls within a frustum of a camera, later you have to check if it's not blocked by any object via Raycasting.