Best practice for destroying objects that are out of the screen in 2D games?

Hi,

In 2D games like Fruit Ninja that objects that are out of the screen are needed to be removed, what’s the practice to do so?

I first thought of putting triggers around the screen and remove objects that enter them but then I thought maybe this approach won’t work on devices with different resolution, as I don’t know what will happen in Unity’s scene on them.

Then I searched and found that you can check with Camera.WorldToScreenPoint and test against pixelWidth and height but was not sure if it’s a good idea.

So what approach do you suggest to do so, and why?

I rather to have a general approach since my objects are spawned outside the screen, then move into the screen and then if player doesn’t interact with them, they will go out, similar to Fruit Ninja. So if I check with Camera, I have to set several flags and it will be somewhat messy.

Thanks.

Most well written games use object pooling rather than creating and destroying objects. Pools can be simple or complex depending on your needs. There is a discussion here:

http://answers.unity3d.com/questions/321762/how-to-assign-variable-to-a-prefabs-child.html

As for detecting when objects are no longer visible, there are many ways. With a 2D game, if you know the widest aspect ratio of the target devices, the easiest solution is to have each object check its world position with respect to the camera. If it is too far in front or behind, above or below, then it is out of view and can be deleted/re-added to the pool. Camera.WorldToScreenPoint() is fine. You might also look at Camera.WorldToViewportPoint() and viewport coordinates. With just one camera, Renderer.isVisible can also be used. You will find a more general discussion of how to detect when the camera can see an object here:

http://answers.unity3d.com/questions/8003/how-can-i-know-if-a-gameobject-is-seen-by-a-partic.html

I was wondering the same question but ran into some problems with renderer.isVisible being false for the first couple frames of some of my objects.

I found a great solution using OnBecameInvisible() here:

ScriptReference:

Use method OnBecameInvisible()