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!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: