# How do I destroy a Unity prefab when it goes off-screen?

I made an infinite path using prefab.Path moving in the negative x direction. I want to destroy the path clone once it goes offscreen.

My path move script is:

var Speed:float = 5;
var hasseen:boolean;
function Start () {
rigidbody2D.velocity.x = -1 * Speed;
hasseen=false;
}
function Update() {
if(renderer.isVisible) {
hasseen=true;
}
if(hasseen) {
if(!renderer.isVisible) {
Destroy(gameObject);
}
}
}


and my prefab script is this:

var path_pre:Transform;
var i:long = 0;
function Update() {
if(i<1000000) {
Instantiate(path_pre, Vector3(i*25, -3, 0), Quaternion.identity);
i++;
}
}

• Rather than polling isVisible many people use OnBecameInvisible()/OnBecameVisible(). Note however that they will report the object as visible if while it is drawn by any camera i.e. the Scene window counts. As a result the game can behave differently in editor. – Kelly Thomas Mar 9 '15 at 12:28

function OnTriggerExit(other) {

This example destroys all game objects which leave the screen. When you want to limit this only to specific objects, make it check the other's name, tag or check if it has a specific component to identify it as an object it is supposed to destroy.