Check if Object is Visible to camera in Unity?

Unity has two inbuild function called OnBecaseVisible and OnBecameInvisible that can be used to detect if an object is visible on the camera or not. There are few things that you need to know before using these functions.

  1. These functions are triggered based on the renderers draw call. So, any object with a renderer should be able to trigger these functions.
  2. Both these functions are triggered even by the scene camera. If you are testing these functions in Unity editor then it will be trigger by the scene camera also.
  3. If you have more than one camera then these functions can be triggered by anyone of them.
  4. Both OnBecameVisible and OnBecameInvisible are called only once when the visibility state is changed.
  5. The function can be added to multiple scripts on the same object. The renderer sends the message to all scripts attached to the gameobject.

With all these in mind let’s see how to use these functions.

Here is a simple example script to use OnBecomeVisible and OnBecomeInvisible. You can check out the YouTube video below for demo of this script

using UnityEngine;
public class test_scrip : MonoBehaviour
{
    Animator anim;
    void Start()
    {
        anim=GetComponent<Animator>();
    }
    void OnBecameInvisible()
    {
        Debug.Log("Enemy Invisible");
        anim.enabled=true;
    }
    void OnBecameVisible()
    {
        Debug.Log("Enemy Visible");
        anim.enabled=false;
    }

}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from VionixStudio

Subscribe now to keep reading and get access to the full archive.

Continue reading