Home > database >  Is there a way to change the Text content of TextMeshPro using Animator?
Is there a way to change the Text content of TextMeshPro using Animator?

Time:05-31

I'm using Animator to create an On/Off toggle button.

I tried to make the image change, color change, text change.

As a result, I changed the image and color, but I don't know how to change the text content. I don't see the fields that the animator adds.

Is it impossible to change text content with an animator?

CodePudding user response:

The short answer to your question is no, you can not apply the effect known as Type Writer in Unity animation. But the code below solves your problem. The code below is a basic Type Writer effect that works by calling Coroutine. Set your TextMeshProUGI to the first parameter and the effect will be done.

public TextMeshProUGUI tmp;
public void Start()
{
    StartCoroutine(TypeWriter("Your text here..", .2f));
}
public IEnumerator TypeWriter(string text, float waitTime)
{
    for (var i = 0; i < text.Length; i  )
    {
        tmp.text = text.Substring(0, i);

        yield return new WaitForSecondsRealtime(waitTime);
    }
}

How to Add Type Writer Effect to Animator?

Here I suggest a good way to apply this effect in the animator. Click on the state you want in the animator and click AddBehavior for creating Type Writer Script.

enter image description here

enter image description here

Finally, all you have to do is reference the script to the OnStateEnter event. I have called the script here from my MenuManager singleton, you can also put it inside your animator character.

public class TypeWriter : StateMachineBehaviour
{
    public string text;
    public float waitTime;
    public override void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    {
        MenuManager.singleton.StartCoroutine(TypeWriter(text, waitTime)); // reference your mono behaviour script here
    }
}

If you have written a script type writer inside the animator character, you can get it below. Remember to replace your script name with Character type on bellow, also IEnumerator can only be used in mono behavior.

public override void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
    animator.GetComponent<Character>().StartCoroutine(TypeWriter(text, waitTime)); // reference your mono behaviour script here
}
  • Related