Scripting a Static Sprite Batcher


You can generate a static sprite batcher in code. This lets you create complex static geometry quickly - often far more efficiently than creating the same number of loose sprites. Use something like this when you need to build a static game board procedurally from script, etc.

DynamicCreateBatcher.cs
using UnityEngine;
using System.Collections;

public class DynamicCreateBatcher : MonoBehaviour {

    // we are just using one sprite collection for all sprites here, but
    // you can have as many as you like.
    public tk2dSpriteCollectionData spriteCollection;

    void Awake() {
        GameObject go = new GameObject();

        tk2dStaticSpriteBatcher batcher = go.AddComponent<tk2dStaticSpriteBatcher>();
        batcher.batchedSprites = new tk2dBatchedSprite[20];

        for (int i = 0; i < batcher.batchedSprites.Length; ++i) {
            tk2dBatchedSprite bs = new tk2dBatchedSprite();

            // assign sprite collection and sprite Id for this batched sprite
            bs.spriteCollection = spriteCollection;
            bs.spriteId = spriteCollection.GetSpriteIdByName("crate");

            Vector3 pos = new Vector3((i - batcher.batchedSprites.Length / 2) * 0.1f, Random.value * 0.2f, 0);

            // Assign the relative matrix. Use this in place of bs.position
            bs.relativeMatrix.SetTRS(pos, Quaternion.identity, Vector3.one);

            batcher.batchedSprites[i] = bs;
        }

        // Don't create colliders when you don't need them. It is very expensive to
        // generate colliders at runtime.
        batcher.SetFlag( tk2dStaticSpriteBatcher.Flags.GenerateCollider, false );

        batcher.Build();
    }
}

This example uses the relativeMatrix.SetTRS pattern to set the relative matrix of each of these objects. The relative matrix is relative to the position of the static sprite batcher, setting a TRS of Vector3(0, 0, 0) will create the sprite at the location of the static sprite batcher, allowing you to move it where you need to later. You can simply use whatever value you used for position using the older system.

If you have legacy code you wish to port - simply call batcher.UpdateMatrices(); before batcher.Build() to update the matrices appropriately.

As of 2D Toolkit 2.0, each entry in the static sprite batcher can have its own sprite collection. Keep in mind that this will add draw calls to the batcher.

Note: Turn off collider generation () when you do not need them - normal colliders are merged into a mesh collider in the static sprite batcher, and this can be quite expensive to generate.

You can also add text meshes, sliced sprites, etc. but these aren't officialy supported and are subject to change.