Scripting a Text Mesh


You can easily access the tk2dTextMesh behaviour from code to control various parameters. In this example, we will be adding a score counter which increases when the Q key is held down. Create a C# script called TextMeshExample, and paste the following code block into it.

TextMeshExample.cs

using UnityEngine;
using System.Collections;

public class TextMeshExample : MonoBehaviour {

    tk2dTextMesh textMesh;
    int score = 0;

    // Use this for initialization
    void Start () {
        textMesh = GetComponent<tk2dTextMesh>();
    }

    // Update is called once per frame
    void Update () {
        if (Input.GetKey(KeyCode.Q))
        {
            score++;
            
            textMesh.text = "SCORE: " + score.ToString();
            
            // This is important, your changes will not be updated until you call Commit()
            // This is so you can change multiple parameters without reconstructing
            // the mesh repeatedly
            textMesh.Commit();
        }
    }
}

TextMeshExample.js

#pragma strict

private var textMesh : tk2dTextMesh;
textMesh = GetComponent(tk2dTextMesh);

private var score = 0;

// Update is called once per frame
function Update() {
    if (Input.GetKey(KeyCode.Q))
    {
        score++;

        textMesh.text = "SCORE: " + score.ToString();

        // This is important, your changes will not be updated until you call Commit()
        // This is so you can change multiple parameters without reconstructing
        // the mesh repeatedly
        textMesh.Commit();
    }
}

Attach this script to the text mesh in the scene, and press play to start the game. Observe that the score text increases when the Q key is held down.

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

textMesh.scale = Vector3(xScale, yScale, zScale);

You can also change the text color by:

textMesh.color = Color.red;

If you have Use Gradient enabled, you can change the second gradient color by:

textMesh.color2 = Color.green;

NOTE: While you can change the maxChars field in code, you should avoid that during runtime as it will reallocate memory.