# Unity2D: Delete spawn objects once it exits camera's view

does anyone know how to delete/destoy a spawn object when it exit out of the camera view. I tried using:

   void OnBecameVisible() {
Destroy (gameObject);
}


But it didn't work. Maybe I'm doing something wrong, I don't know. Oh just a friendly advice my spawned object may enter form any point of the screen. Thank you :).

• Why would you be checking if the object was visible, when it is literally the exact opposite of being not visible? Aug 21 '16 at 2:54

Try with OnBecameInvisible instead.

Try this:

var obj : Transform;
if (raycast.transform != obj)
Destroy(obj.gameObject);


where obj is your object. This needs to be applied to your camera. This should work.

• Thank you, but could you convert it to c# . Please and Thank you Aug 20 '16 at 20:38
• I usally use javascript, but here you go: public Transform //name of object//; if (RaycastHit.transform != //name of object//) { Destroy(//name of object//) } Aug 20 '16 at 20:50
• Thank you, I'll try it out once I fix unity, I'm having a bug Aug 20 '16 at 20:56
• Alright, and make sure to vote for my answer! Aug 20 '16 at 20:58
• @TheMattBat999, this answer confused me. Especially considering a far easier to understand solution was posted not 20 seconds after yours. You have raised, previously, that you are "just trying to help". Since you mean well, I thought I would address that this site favors quality over quantity. You might mean well, but if you keep posting answers that get down-voted, the system actually blocks you from posting any more answers. Test out your material, assume the audience is not "a genius" like you, and consider formatting to make your answers more presentable. Aug 21 '16 at 3:02