My 2D Unity game has tiles and layers. It creates one game object per tile, anywhere from 100 to 10,000. To create 3,000 game objects takes 68 msec, which is just fine.
But setting up the sprite and location takes 5,000 msec, or nearly 2 msec per sprite. This is a problem. Here is the code for setting up each tile.
var sprite = _main.GetSprite(LevelIndex); // pre-computed table of sprites
_renderer.sprite = sprite; // the sprite renderer for the tile
if (sprite != null) {
var cursize = _renderer.sprite.bounds.size;
var scale = Math.Max(Size.x / cursize.x, Size.y / cursize.y);
transform.localScale = new Vector3(scale, scale, 0);
}
How can that code take 2 msec? What's going on?
The sprite size is 80x80. Is this a problem?
Once it's all set up it renders at 100 fps easily. So why is the setup so slow, and what can I do about it?
Yes, I considered using a TileMap. It's not easy to see how to create one in fully procedural code, but at the heart of it is the Tile class, which has a GameObject and a Sprite. If I implement my own Tile class it's going to have code that looks a lot like the above, and (after a lot of work) most likely perform exactly the same.
Since Tile and TileMap are just layers over standard Unity infrastructure, then if they do have a way to perform much faster, I should be able to apply the same technique to my situation and get the same performance.
_renderer.sprite
property does far more than just a simple setter. But without proper profiling, this is just a wild guess. \$\endgroup\$ – Philipp Apr 5 '18 at 14:53