# 5. PlayableDirector Control and Runtime Binding Part of [[Timeline Advanced]]. Previous: [[4. Signals and Custom Markers]]. Next: [[6. Cutscene Controller and Handing Control Back]]. > [!warning] Code not compiled in Unity > Type-checked against Unity 6000.5.8f1 assemblies and Timeline 1.8.13 (see the hub). Not compiled or run in the Editor. ## 5.1 Events `PlayableDirector` raises three C# events, each passing the director: - `played` - `Play()` was called (and, per the Timeline changelog, also after entering or exiting Play Mode). - `paused` - `Pause()` was called. - `stopped` - `Stop()` was called, **or** a timeline with Wrap Mode **None** reached its end. Subscribe in `OnEnable`, unsubscribe in `OnDisable`. A lambda you cannot unsubscribe is a leak on a long-lived director. ## 5.2 Wrap mode decides how a cutscene can end `extrapolationMode` (Inspector: **Wrap Mode**) is a `DirectorWrapMode`: | Mode | At the end | `stopped` fires? | Bound objects after the end | |---|---|---|---| | **None** | Graph is destroyed, director stops | **Yes** | Tracks stop driving them; what remains depends on the track (Activation track's post-playback state, your mixers' restore logic, the Animator returning to its controller) | | **Hold** | Keeps evaluating the last frame | **No** | Held in the final pose until you `Stop()` | | **Loop** | Wraps to 0 | No | | The trade-off for a gameplay cutscene: - **None** gives you a clean `stopped` event, but anything you only *animated* (a door rotated by an Animation track) may stop being held. Make the end state **real gameplay state** instead: the gate's component sets its own open pose on `gate.open` (part 4). - **Hold** keeps the last frame, but nothing tells you it ended, and a Cinemachine shot still active on that last frame keeps overriding the camera. Part 6 polls `time >= duration` for Hold, and you should end the last Cinemachine shot (with an ease-out) *before* the timeline ends. Part 6 supports both. A good default is **None plus state events**. ## 5.3 Update mode and pausing `timeUpdateMode` is a `DirectorUpdateMode`: | Mode | Clock | Good for | |---|---|---| | `GameTime` | scaled `Time.deltaTime` | most cutscenes; `Time.timeScale = 0` freezes it | | `UnscaledGameTime` | unscaled time | UI sequences that must run while the game is paused | | `DSPClock` | the audio DSP clock | music-locked sequences | | `Manual` | you set `time` and call `Evaluate()` | lockstep, replays, deterministic tests | For a **pause menu**, call `director.Pause()` and `Resume()` from the pause flow ([[Menus, Pause and Settings Flow]] / [[4. Pause Menu Time Scale and Audio]]) rather than relying on `timeScale = 0` alone. Audio tracks are played by the audio system, and depending on how your pause handles `AudioListener.pause` they may not stop with the timescale. An explicit `Pause()` stops everything in the graph together. The `CutsceneController.AnyStarted` / `AnyFinished` events in part 6 let the pause menu know a cutscene is running. ## 5.4 Evaluate versus Play - `Play()` advances time on its clock and **fires markers**. - `Evaluate()` applies the timeline at the current `time` **without advancing and without firing markers** (part 4). Use it for previews, scrubbing UI and the first frame of a manual sequence. - `Manual` update mode with `Evaluate()` therefore never fires markers. If you need markers under a manual clock, try `director.playableGraph.Evaluate(deltaTime)`; whether that counts as playback for markers was **not verified**, so test it before you depend on it. ```csharp // Assets/TimelineAdvanced/Runtime/DirectorRecipes.cs using UnityEngine; using UnityEngine.Playables; using UnityEngine.Timeline; namespace TimelineAdvanced { // Small, copyable PlayableDirector recipes used in part 5. public static class DirectorRecipes { // Scrub/preview: apply the timeline at an exact time without playing. // Evaluate() is a scrub, so markers and Signals do NOT fire. public static void ShowFrame(PlayableDirector director, double time) { director.time = System.Math.Clamp(time, 0.0, director.duration); director.Evaluate(); } // Start playback part-way through (for example after a checkpoint reload). // Markers before 'time' fire only if they are Retroactive. public static void PlayFrom(PlayableDirector director, double time) { director.time = System.Math.Clamp(time, 0.0, director.duration); director.Play(); } // Pause without tearing the graph down (state is kept; Resume continues). public static void TogglePause(PlayableDirector director) { if (director.state == PlayState.Playing) director.Pause(); else if (director.playableGraph.IsValid()) director.Resume(); } // Manual update mode: you own the clock (lockstep, replays, a custom pause). // Call from Update or a fixed-step loop. public static void StepManually(PlayableDirector director, double deltaTime) { if (director.timeUpdateMode != DirectorUpdateMode.Manual) director.timeUpdateMode = DirectorUpdateMode.Manual; if (!director.playableGraph.IsValid()) director.RebuildGraph(); director.time = System.Math.Min(director.time + deltaTime, director.duration); director.Evaluate(); } // Time of the first marker of type T on the Markers row or any track, or -1. public static double FindFirstMarkerTime<T>(TimelineAsset timeline) where T : class, IMarker { double best = double.MaxValue; if (timeline.markerTrack != null) foreach (IMarker m in timeline.markerTrack.GetMarkers()) if (m is T && m.time < best) best = m.time; foreach (TrackAsset track in timeline.GetOutputTracks()) foreach (IMarker m in track.GetMarkers()) if (m is T && m.time < best) best = m.time; return best == double.MaxValue ? -1.0 : best; } } } ``` ## 5.5 Binding at runtime **Tracks bind through the director, not the asset.** `director.playableAsset.outputs` lists one `PlayableBinding` per track output; its `sourceObject` is the track, its `streamName` is the track's name. `SetGenericBinding(track, obj)` sets what that track drives in this director. **ExposedReferences** (clip fields like part 1's `target`, a Control clip's source object, a Cinemachine shot's camera) are set with `SetReferenceValue(exposedName, obj)`. The id is on the clip asset: `clipAsset.target.exposedName`. **Rebuild.** Bindings are read when the graph is built. Set them *before* `Play()`, or call `RebuildGraph()` if the graph already exists. `RebuildGraph` keeps the current time. ```csharp // Assets/TimelineAdvanced/Runtime/CutsceneBinder.cs using System; using System.Collections.Generic; using UnityEngine; using UnityEngine.Playables; using UnityEngine.Timeline; using Object = UnityEngine.Object; namespace TimelineAdvanced { // Binds tracks by name at runtime, so one TimelineAsset can be reused with different // actors (spawned NPCs, the current player prefab, a pooled boss). [RequireComponent(typeof(PlayableDirector))] public class CutsceneBinder : MonoBehaviour { [Serializable] public struct NamedBinding { public string trackName; // exact track name in the Timeline window public Object target; // Animator, Light, SubtitleView, GameObject, ... } [SerializeField] List<NamedBinding> bindings = new List<NamedBinding>(); PlayableDirector m_Director; void Awake() { m_Director = GetComponent<PlayableDirector>(); foreach (NamedBinding b in bindings) BindTrack(b.trackName, b.target, rebuild: false); RebuildIfBuilt(); } // Returns how many outputs were bound. Tracks can share a name; all matches are bound. public int BindTrack(string trackName, Object target, bool rebuild = true) { if (m_Director == null) m_Director = GetComponent<PlayableDirector>(); if (m_Director.playableAsset == null) return 0; int count = 0; foreach (PlayableBinding output in m_Director.playableAsset.outputs) { if (output.streamName != trackName || output.sourceObject == null) continue; m_Director.SetGenericBinding(output.sourceObject, target); count++; } if (count == 0) Debug.LogWarning(quot;[CutsceneBinder] No track named '{trackName}' in {m_Director.playableAsset.name}", this); if (rebuild) RebuildIfBuilt(); return count; } // Sets the scene object behind an ExposedReference (for example a clip's target field). // Read the id from the clip asset: myClip.target.exposedName public void SetExposedReference(PropertyName exposedName, Object value) { m_Director.SetReferenceValue(exposedName, value); RebuildIfBuilt(); } // Swap to a different timeline (same director, same receivers), then bind by name. public void UseTimeline(TimelineAsset timeline) { m_Director.playableAsset = timeline; foreach (NamedBinding b in bindings) BindTrack(b.trackName, b.target, rebuild: false); RebuildIfBuilt(); } // Slow motion or fast-forward of the whole cutscene without touching Time.timeScale. public void SetPlaybackSpeed(double speed) { if (m_Director.playableGraph.IsValid() && m_Director.playableGraph.GetRootPlayableCount() > 0) m_Director.playableGraph.GetRootPlayable(0).SetSpeed(speed); } public static T FindTrack<T>(TimelineAsset timeline, string trackName) where T : TrackAsset { foreach (TrackAsset track in timeline.GetOutputTracks()) if (track is T typed && track.name == trackName) return typed; return null; } void RebuildIfBuilt() { // Bindings are read when the graph is built. If it already exists, rebuild it // so the new bindings take effect. RebuildGraph keeps the current time. if (m_Director.playableGraph.IsValid()) m_Director.RebuildGraph(); } } } ``` **Typical uses:** - **Spawned actors.** The NPC in the cutscene is the one that spawned this run: `binder.BindTrack("Guard Animation", guard.GetComponent<Animator>())`. - **Prefab cutscenes.** One cutscene prefab used in several scenes: bind the scene's `CinemachineBrain` to the Cinemachine track and the scene's `SubtitleView` to the subtitle track by name in `Awake`. - **Variants.** `UseTimeline(shortVersion)` for a replay, the full version on first view. **Rebinding Cinemachine shots.** A Cinemachine Shot clip's camera is an `ExposedReference<CinemachineVirtualCameraBase>` field named `VirtualCamera` on `CinemachineShot`, so `director.SetReferenceValue(shot.VirtualCamera.exposedName, myCamera)` points a shot at a scene camera. The Cinemachine 3.1.7 source marks `CinemachineShot` as "internal use only, not part of the public API" even though the class and field are public, so this may change between versions. Bind the **Cinemachine track** itself to the **CinemachineBrain** (on the Main Camera). **Speed.** `playableGraph.GetRootPlayable(0).SetSpeed(0.5)` slows the whole cutscene without touching `Time.timeScale`, so gameplay systems that run during it (ambient AI, physics props) are not slowed. The root playable is the TimelinePlayable in current versions; this index-0 assumption is common practice, not a documented contract. ## 5.6 Awaiting a cutscene Part 6's controller has `PlayAndWaitAsync(CancellationToken)`, which polls with `Awaitable.NextFrameAsync` until the controller is idle again. That makes sequencing readable: - a boss intro: `await intro.PlayAndWaitAsync(destroyCancellationToken); bossFsm.Begin();` ([[Boss Battles with Phases]] / [[4. Timeline Intros and Phase Transitions]]), - a level start: load the scene, `await` the intro, then show the objective. Pass `destroyCancellationToken` so the wait ends if the caller is destroyed. Awaitables, cancellation and the "awaiting twice" trap are covered in [[Async Code]] / [[3. Cancellation Tokens]]. ## 5.7 Exercise Make one `Cutscene_Greeting` prefab with a timeline that has tracks named `Speaker Animation` and `Subtitles`. Place it in two scenes with different NPCs. In each scene, bind by name in `Awake` and play. Then swap the NPC at runtime while the cutscene is paused and call `BindTrack` again: confirm `RebuildGraph` keeps the time. ## Sources - `PlayableDirector` (6000.5): https://docs.unity3d.com/6000.5/Documentation/ScriptReference/Playables.PlayableDirector.html - `DirectorWrapMode` (6000.5): https://docs.unity3d.com/6000.5/Documentation/ScriptReference/Playables.DirectorWrapMode.html - `DirectorUpdateMode` (6000.5): https://docs.unity3d.com/6000.5/Documentation/ScriptReference/Playables.DirectorUpdateMode.html - Playable Director component (Timeline 1.8 manual): https://docs.unity3d.com/Packages/[email protected]/manual/playable-director.html - `Awaitable` (6000.5): https://docs.unity3d.com/6000.5/Documentation/ScriptReference/Awaitable.html - Cinemachine and Timeline (3.1): https://docs.unity3d.com/Packages/[email protected]/manual/concept-timeline.html - Timeline 1.8 changelog (`played` after entering/exiting Play Mode): https://docs.unity3d.com/Packages/[email protected]/changelog/CHANGELOG.html