Custom Event Handlers

Using events in custom MonoBehaviours

When the Animated Text Events component is not good enough or too inconvenient to use, you may want to register your own event listeners. After reading this short guide, I recommend looking at the code of the built-in event handlers and the Example Dialogue component, from the example scene, for inspiration.

  1. To get started, your component needs a reference to the UI Document containing your animated text element.

  2. Then you can use TextAnimationUtility.GetAnimatedTextElement to find your text element. If you need a specific type of animated text element instead of the interface IAnimatedTextElement, use uiDocument.rootVisualElement.Q<AnimatedLabel>("dialogue-box") instead.

  3. Register handlers for the events you're interested in.

  4. Make sure to unregister all events in OnDisable, or your component will continue working when disabled.

public class CustomEventHandler : MonoBehaviour
{
    // 1. Reference your UI Document
    [SerializeField]
    private UIDocument uiDocument;

    private IAnimatedTextElement _dialogueBox;

    private void OnEnable()
    {
        // 2. Find your animated text element
        _dialogueBox = TextAnimationUtility.GetAnimatedTextElement(uiDocument, "dialogue-box");
        
        // 3. Register the events you're interested in
        _dialogueBox.animationEvent += OnAnimationEvent;
        _dialogueBox.letterAppeared += OnLetterAppeared;
        _dialogueBox.textAppearanceFinished += OnTextAppearanceFinished;
    }

    private void OnDisable()
    {
        // 4. Unregister your events in OnDisable, 
        // or your component will continue to work when disabled.
        _dialogueBox.animationEvent -= OnAnimationEvent;
        _dialogueBox.letterAppeared -= OnLetterAppeared;
        _dialogueBox.textAppearanceFinished -= OnTextAppearanceFinished;
    }

    private void OnAnimationEvent(TextAnimationEvent ev)
    {
        Debug.Log("Received animation event");
    }

    private void OnLetterAppeared(LetterAppearanceEvent ev)
    {
        Debug.Log("Received letter appearance event for letter: " + ev.letter);
    }

    private void OnTextAppearanceFinished(TextAppearanceFinishedEvent ev)
    {
        Debug.Log("Received text appearance finished event");
    }
}

Are you stuck? Maybe you need another kind of event that isn't supported yet?

Contact me via the contact form, or join my Discord and I'll try my best to help you!

Last updated

Was this helpful?