# 3. Subtitle and Dialogue Track Part of [[Timeline Advanced]]. Previous: [[2. Custom Light Intensity Track with a Mixer]]. Next: [[4. Signals and Custom Markers]]. > [!warning] Code not compiled in Unity > C# type-checked against Unity 6000.5.8f1 assemblies and Timeline 1.8.13 (see the hub). UXML and USS were not checked at all. Nothing was run in the Editor. Subtitles are the textbook case for a custom track: they are **timed**, they **overlap** during hand-offs between speakers, and they must be **readable**. The Timeline Customization samples include a `TextTrack` for `TMP_Text`; this version binds to a small UI Toolkit view component instead, which keeps layout, styling and accessibility in one place. ## 3.1 Why bind to a view component The track's binding type is `SubtitleView`, not `Label`. The track never knows the UI layout; the view owns its UXML, finds its labels and can apply the player's subtitle settings. That is the **Component** pattern from [[Game Programming Patterns (Review)]], and it means a VR build can swap in a world-space view without touching the timeline (see [[UI Toolkit and Diegetic UI]]). ## 3.2 UI: UXML and USS `Assets/TimelineAdvanced/UI/Subtitles.uxml`: ```xml <ui:UXML xmlns:ui="UnityEngine.UIElements"> <Style src="Subtitles.uss" /> <ui:VisualElement name="subtitle-root" class="subtitle-root" picking-mode="Ignore"> <ui:Label name="subtitle-speaker" class="subtitle-speaker" picking-mode="Ignore" /> <ui:Label name="subtitle-line" class="subtitle-line" picking-mode="Ignore" /> </ui:VisualElement> </ui:UXML> ``` `Assets/TimelineAdvanced/UI/Subtitles.uss`: ```css .subtitle-root { position: absolute; left: 10%; right: 10%; bottom: 6%; padding: 10px 18px; background-color: rgba(0, 0, 0, 0.6); border-radius: 6px; align-items: center; } .subtitle-speaker { -unity-font-style: bold; color: rgb(255, 214, 102); font-size: 22px; } .subtitle-line { white-space: normal; -unity-text-align: middle-center; color: rgb(255, 255, 255); font-size: 26px; } ``` Create a GameObject `Subtitles` with a **UIDocument** (Panel Settings shared with your HUD, Source Asset `Subtitles.uxml`, a Sort Order above the HUD) and add `SubtitleView`. ## 3.3 The view ```csharp // Assets/TimelineAdvanced/Runtime/SubtitleView.cs using System; using UnityEngine; using UnityEngine.UIElements; namespace TimelineAdvanced { // The subtitle track binds to this component, not to a Label directly, so the track // never needs to know the UI layout (Component pattern: the view owns its UI). [RequireComponent(typeof(UIDocument))] public class SubtitleView : MonoBehaviour { [SerializeField] string rootName = "subtitle-root"; [SerializeField] string speakerLabelName = "subtitle-speaker"; [SerializeField] string lineLabelName = "subtitle-line"; // Raised once per new line (not every frame). Use it for a dialogue log, // analytics, or an accessibility caption history. public event Action<string, string> LineShown; VisualElement m_Root; Label m_Speaker; Label m_Line; string m_LastKey; void OnEnable() { m_Root = null; // the UIDocument rebuilds its tree on enable Clear(); } bool Bind() { if (m_Root != null && m_Root.panel != null) return true; var document = GetComponent<UIDocument>(); if (document == null || document.rootVisualElement == null) return false; VisualElement tree = document.rootVisualElement; m_Root = tree.Q<VisualElement>(rootName); m_Speaker = tree.Q<Label>(speakerLabelName); m_Line = tree.Q<Label>(lineLabelName); return m_Root != null && m_Speaker != null && m_Line != null; } public void Show(string speaker, string line, float alpha) { if (!Bind()) return; m_Root.style.display = DisplayStyle.Flex; m_Root.style.opacity = Mathf.Clamp01(alpha); m_Speaker.text = speaker; m_Speaker.style.display = string.IsNullOrEmpty(speaker) ? DisplayStyle.None : DisplayStyle.Flex; m_Line.text = line; string key = speaker + "\u001f" + line; if (key != m_LastKey) { m_LastKey = key; LineShown?.Invoke(speaker, line); } } public void Clear() { m_LastKey = null; if (!Bind()) return; m_Root.style.display = DisplayStyle.None; } } } ``` `LineShown` fires once per new line, not every frame. Hook it to a dialogue log ("previous lines" screen), analytics, or a caption history for [[Accessibility]]. ## 3.4 Clip data and clip asset The text fields are `[NotKeyable]`: animating a string in the Curves view makes no sense, and it keeps the clip inspector tidy. ```csharp // Assets/TimelineAdvanced/Runtime/SubtitleBehaviour.cs using System; using UnityEngine; using UnityEngine.Playables; using UnityEngine.Timeline; namespace TimelineAdvanced { [Serializable] public class SubtitleBehaviour : PlayableBehaviour { [NotKeyable] public string speaker = "Guard"; [NotKeyable, TextArea(2, 4)] public string line = "The gate stays shut until the bell rings."; } } ``` ```csharp // Assets/TimelineAdvanced/Runtime/SubtitleClip.cs using System; using UnityEngine; using UnityEngine.Playables; using UnityEngine.Timeline; namespace TimelineAdvanced { [Serializable] public class SubtitleClip : PlayableAsset, ITimelineClipAsset { // Reading-speed guide used by the clip editor's warning. A common subtitling // rule of thumb is roughly 15-20 characters per second; tune it for your audience. public const float MaxCharactersPerSecond = 17f; public SubtitleBehaviour template = new SubtitleBehaviour(); // Blending gives ease-in/out, which the mixer turns into a fade. public ClipCaps clipCaps => ClipCaps.Blending; public override double duration => 3.0; public override Playable CreatePlayable(PlayableGraph graph, GameObject owner) { return ScriptPlayable<SubtitleBehaviour>.Create(graph, template); } // Minimum seconds a line should stay on screen at the guide reading speed. public float MinimumReadSeconds() { int characters = template.line != null ? template.line.Length : 0; return Mathf.Max(1f, characters / MaxCharactersPerSecond); } } } ``` `MinimumReadSeconds` feeds part 7's clip editor, which marks clips that are too short to read. The 17 characters per second constant is a rule of thumb, not a standard; for a younger audience or a second-language class, lower it. ## 3.5 The mixer: pick, do not average Colors and intensities can be averaged; sentences cannot. The mixer picks the input with the **greatest weight** and uses that weight as the opacity. During an overlap the outgoing line fades out until the incoming one outweighs it, then the incoming line is shown fading in. With ease-in/out on each clip, that reads as a cross-fade. ```csharp // Assets/TimelineAdvanced/Runtime/SubtitleMixerBehaviour.cs using UnityEngine.Playables; namespace TimelineAdvanced { // Text cannot be averaged, so this mixer picks the clip with the greatest weight // and uses that weight as the opacity (ease-in/out becomes a fade). public class SubtitleMixerBehaviour : PlayableBehaviour { SubtitleView m_View; public override void ProcessFrame(Playable playable, FrameData info, object playerData) { m_View = playerData as SubtitleView; if (m_View == null) return; int inputCount = playable.GetInputCount(); float bestWeight = 0f; SubtitleBehaviour best = null; for (int i = 0; i < inputCount; i++) { float weight = playable.GetInputWeight(i); if (weight <= bestWeight) continue; var input = (ScriptPlayable<SubtitleBehaviour>)playable.GetInput(i); best = input.GetBehaviour(); bestWeight = weight; } if (best == null || bestWeight <= 0.001f) m_View.Clear(); else m_View.Show(best.speaker, best.line, bestWeight); } public override void OnPlayableDestroy(Playable playable) { if (m_View != null) m_View.Clear(); m_View = null; } } } ``` ## 3.6 The track ```csharp // Assets/TimelineAdvanced/Runtime/SubtitleTrack.cs using System.ComponentModel; using UnityEngine; using UnityEngine.Playables; using UnityEngine.Timeline; namespace TimelineAdvanced { [TrackColor(0.35f, 0.65f, 0.95f)] [TrackClipType(typeof(SubtitleClip))] [TrackBindingType(typeof(SubtitleView))] [DisplayName("Timeline Advanced/Subtitle Track")] public class SubtitleTrack : TrackAsset { public override Playable CreateTrackMixer(PlayableGraph graph, GameObject go, int inputCount) { return ScriptPlayable<SubtitleMixerBehaviour>.Create(graph, inputCount); } protected override void OnCreateClip(TimelineClip clip) { if (clip.asset is SubtitleClip subtitle) clip.displayName = subtitle.template.speaker; } } } ``` There is no `GatherProperties` here: the view writes UI Toolkit styles and label text, not serialized component fields, so there is nothing for preview mode to record. `OnPlayableDestroy` clears the view instead. ## 3.7 Use it 1. **+ > Timeline Advanced > Subtitle Track**, bind the `Subtitles` object (its `SubtitleView`). 2. Add a clip per line. Give each about 0.2 s Ease In and Out. Overlap consecutive lines by about 0.2 s. 3. Add an **Audio Track** above it for the voice-over, one audio clip per line, aligned with the subtitle clips. For mixer routing and ducking music under VO see [[Audio Mixers and Character Audio]]. 4. Scrub in Edit Mode. UIDocument panels normally draw in the Game view outside Play Mode, and `SubtitleView` binds lazily on the first `Show`, so subtitles should preview while you scrub (not verified for this exact setup; if nothing shows, check the Game view is open and the UIDocument has Panel Settings). ## 3.8 Accessibility and localization - **Size and background.** [[3. Subtitle Scale and Captions]] stores a subtitle scale and background opacity setting. Apply it in `SubtitleView` (for example add a USS class per size, or multiply the labels' `style.fontSize`), never in the track. The track stays the same for every player. - **Speaker names and colors** help players who cannot hear which voice is speaking. Keep the speaker label even when the speaker is on screen. - **Localization.** For shipped text, swap `line` for a `LocalizedString` (Localization package) and resolve it when the graph is built or when the line becomes active. The string-table setup and pseudo-localization are in [[Localization]] / [[6. Localizing Game Data Dialogue and Pseudo-Localization]]. Not shown here because it adds a package dependency; resolving a `LocalizedString` synchronously can stall if the table is not loaded yet, so preload the table before the cutscene. ## 3.9 Linear lines versus interactive dialogue This track is for **linear** lines, the "watch" part of a cutscene. For a choice in the middle, follow Level 17 of [[Level Up! (Review)]] ("better to have the player do than watch"): 1. Put a `GameplayEventMarker` (part 4) with id `dialogue.choice` where the choice belongs. 2. Its receiver calls `director.Pause()` and starts your branching dialogue ([[0.Dialogue System]] or [[Conversation Engine Design for Unity 6]]; [[TypewriterEffect.cs]] for reveal). 3. When the dialogue reports it has finished, call `director.Resume()`. Optionally jump to a branch with `director.time = branchTime` first. `Pause` keeps the graph alive: bound objects hold their poses and the Cinemachine shot holds. Because the player now *is* interacting, part 6's controller should switch to the UI action map rather than leave the Cutscene map active (exercise in part 6). ## 3.10 Exercise Add a `Color speakerColor` field to the behaviour, pass it through `SubtitleView.Show`, and set `m_Speaker.style.color`. Then add a toggle in the view that hides the speaker label, and check it from the [[Accessibility]] settings. ## Sources - Timeline Customization samples (Text track: highest-weight text, defaults, restore): https://docs.unity3d.com/Packages/[email protected]/manual/samp-custom-samples.html - `NotKeyableAttribute` (Timeline 1.8): https://docs.unity3d.com/Packages/[email protected]/api/UnityEngine.Timeline.NotKeyableAttribute.html - UI Toolkit `UIDocument` (6000.5): https://docs.unity3d.com/6000.5/Documentation/ScriptReference/UIElements.UIDocument.html - `PlayableDirector.Pause` / `Resume` (6000.5): https://docs.unity3d.com/6000.5/Documentation/ScriptReference/Playables.PlayableDirector.html See also (added 2026-11-27): [[Ink Narrative Integration]] / [[4. Story Loop and UI Toolkit Presenter]] - the same speaker-and-body view can be driven from an Ink runner during a cutscene; skip still has to account for EXTERNAL grants.