What's the best way to instantiate a sprite and get its renderer

I’m making a 2D open world game and I’d like to use object pooling to prevent constantly instantiating and destroying the terrain as the player moves around (chunk loading). To quickly reuse the object I’d need to change its sprite.

The problem I’m facing is Instantiating a prefab then immediately calling GetComponent<SpriteRenderer>(); seems to be quite taxing.

I need an efficient way to instantiate a large number of objects (128 to 192 at a time) and have their SpriteRenderers ready in case they get moved elsewhere and need to have their sprites changed.

Any thoughts? Advice? I’m on my knees here.

On second thoughts, it might not actually be so bad. But I’m still open to suggestions.

Well if you’re pooling your objects, you shouldn’t be instantiating anything after the first batch. At that point, the SpriteRenderer would be cached and available for reuse through a variable of some sort. You can also pre-warm the data by simply linking it to itself inside the inspector in the editor.

You should run the profiler and make sure the creation / reuse is actually the cause of the performance loss and not something else.

1 Like