Scripting A Sprite


You can easily access the tk2dSprite behaviour from code to control various parameters. In this example, we will be adding a script to change the color of the box script when a key-press is detected. Create a C# script in your project and call it TutorialSpriteScript. Paste the following code block into the script.

TutorialSpriteScript.cs
using UnityEngine;
using System.Collections;

public class TutorialSpriteScript : MonoBehaviour {
    tk2dSprite sprite;

    void Start() {
        sprite = GetComponent<tk2dSprite>();
    }

    void Update() {
        if (Input.GetKeyDown(KeyCode.A)) {
            sprite.color = Color.red;
        }
        if (Input.GetKeyDown(KeyCode.S)) {
            sprite.color = Color.white;
        }
        if (Input.GetKeyDown(KeyCode.Q)) {
            sprite.scale = new Vector3(2, 2, 2);
        }
        if (Input.GetKeyDown(KeyCode.W)) {
            sprite.SetSprite("crate");
        }
    }
}
TutorialSpriteScript.js
#pragma strict

private var sprite : tk2dSprite;
sprite = GetComponent(tk2dSprite);

function Update() {
    if (Input.GetKeyDown(KeyCode.A)) {
        sprite.color = Color.red;
    }
    if (Input.GetKeyDown(KeyCode.S)) {
        sprite.color = Color.white;
    }
    if (Input.GetKeyDown(KeyCode.Q)) {
        sprite.scale = Vector3(2, 2, 2);
    }
    if (Input.GetKeyDown(KeyCode.W)) {
        sprite.SetSprite("crate");
    }
}

Attach this script to the crate sprite, and press play to start the game. Observe that you can use the A, S, Q & W keys to change various properties of the sprite at runtime.

You can change the scale of the sprite without breaking dynamic batching by:

sprite.scale = new Vector3(xScale, yScale, zScale);

You can also change the displayed sprite by doing:

sprite.SetSprite("crate");

Note that the name is case sensitive.

And you can cache the spriteId and use that instead for better performance:

int spriteId = sprite.GetSpriteIdByName("Rock");
sprite.SetSprite(spriteId);