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.
That's it! Just a few line of codes and you can destroy the game object when it is off screen. Thank you!
Copyright © 2024 Tek Min Ewe