1
votes

I have keyboad prefab and 6 keys prefab. I put keys with Instantiate. Every keys have got TextMeshPro objects. I need to change these characters with script. But when I try to get TextMeshPro component, console returns null.

Debug.Log(GetComponent<TextMeshPro>());

enter image description here

My code part is here;

private void SetUp()
{
    // Global Screen Height
    var worldScreenHeight = Camera.main.orthographicSize * 2.0;
    // Global Screen Width
    var worldScreenWidth = worldScreenHeight / Screen.height * Screen.width;
    // Keyboard
    var keyboardSize = GetComponent<SpriteRenderer>().sprite.bounds.size.x;
    var neededScale = worldScreenWidth / keyboardSize;
    var neededYPosition = (worldScreenHeight / 2) - (keyboardSize / 2);
    transform.localScale = new Vector3((float)neededScale, (float)neededScale, 0);
    transform.position = new Vector3(0, -(float)neededYPosition, 0);
    for (int i = 0; i < Characters.Length; i++)
    {
        double angle = ((i / (Characters.Length / (double)2)) * Math.PI);
        GameObject newObject = Instantiate(Keys, new Vector2((float)(keyboardSize / 2 * 0.6 * neededScale * Math.Cos(angle)), (float)(keyboardSize / 2 * 0.6 * neededScale * Math.Sin(angle) - neededYPosition)), Quaternion.identity, transform) as GameObject;
        newObject.transform.localScale = new Vector3(0.5f, 0.5f, 0);
        // I can't access textmeshpro
        Debug.Log(GetComponent<TextMeshPro>());
    }

}

How can change strings in TextMeshPro?

1
I'm looking for same answer - Erçin Dedeoğlu
This script is placed in KeyText gameObject or in TMP object (child of KeyText) - Lotan

1 Answers

0
votes

Replace GetComponent<TextMeshPro>() to GetComponent<TextMeshProUGUI>().

There are two TextMeshPro components who both derive from TMP_Text.

The first component of type TextMeshPro is designed to replace the old TextMesh which uses the MeshRenderer.

The 2nd of type TextMeshProUGUI is designed to replace UI.Text and designed to work with the CanvasRenderer and Canvas system, which seems the one you're using.