# How can I reuse objects going off left side of screen, by putting them offscreen on the right side?

I have an array of roughly 10,000 tiles over a 2d grid. When a tile goes off screen, I'd like to recycle it by disabling the renderer, repositioning it just before it comes on screen again, then turn the renderer back on. For example, if the camera is moving right on a platformer, the tiles on the left going off screen would be recycled and repositioned on the right side just before the camera. The player could be moving in any 2d direction, up, up right, right, down right, down, down left, left, up left, thus I need to account for all directions.

    0,0--------------->100, 0
| Move Direction--> |
|                   |
x|xxxxxxxxxxxxxxxxxxx|xxx  <-  Recycled objects taken
x|xxxxxxxxxxxxxxxxxxx|xxx  <-  from left and repositioned on right
0,-100<----------->100,-100


I've tried two approaches, one is using a wider camera view (maybe 1.3x) and using the edges with ViewportToWorldPoint and getting the player horizontal and vertical movement direction. If the camera is moving horizontally one way, my tilemanager script runs down the other side and repositions the objects on the opposite just before coming on screen. The problem here is if one is ever missed, it could go astray and then over time this leads to further problems if over time multiple are missed. I am using a tilemanager and not putting a script in each tile as it seems wasteful to have a script running in 10k+ tiles.

The other approach is literally to just scan every item in the array to see if any are outside the viewport bounding box, which seems like a huge waste of resources and not the right way to go. I have a 2d array that has just the positions saved, nonetheless scanning through any array of 10k+ each frame seems like it isn't the right way to go in terms of efficiency.

All of this work is being done as a coroutine but what is frustrating is that unity doesn't support threading as this would make this task faster as I could divide up the work more.

Is there another way anyone has used or created something that will efficiently find all objects off screen, in order to reuse them?

• Your use of the term "garbage collection" here is extremely confusing, because it has a very specific meaning that I don't think you mean to use. Possibly edit your question and use a different name. I think the term you want to use is "object pool". Dec 14 '13 at 9:24