> For the complete documentation index, see [llms.txt](https://docs.stixgames.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.stixgames.com/text-animations/c-extensions/custom-event-handlers.md).

# 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.&#x20;
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.

```csharp
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?&#x20;

Contact me via the [contact form](https://stixgames.com/contact/), or join my [Discord](https://discord.gg/jvBFhQA) and I'll try my best to help you!
