How To Destroy Object When It Is Out Of Screen In Unity 3D

Today, I would like to share with you how to destroy game object when it is out of screen or no longer visible in Unity 3D. The answer is pretty simple! Just use Renderer.OnBecameInvisible(), this method will be called whenever the game object is visible by any camera.

using UnityEngine;

public class DestroyOnOffScreen : MonoBehaviour {
    void OnBecameInvisible() {
        Destroy (gameObject);

        // If you would like to destroy the top most game object
        // Destroy (transfrom.root.gameObject);

However, there are few potential mistakes that may lead to OnBecameInvisible() is not working.

  1. If the script is attach to the game object that does not have renderer, then OnBecameInvisible() will not be called.
  2. Scene view camera is considered one of the camera, so you may need to hide or close the scene view to trigger OnBecameInvisible() method in Unity Editor.

That’s it! Just a few line of codes and you can destroy the game object when it is off screen. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top