# 6. Cutscene Controller and Handing Control Back Part of [[Timeline Advanced]]. Previous: [[5. PlayableDirector Control and Runtime Binding]]. Next: [[7. Timeline Editor Customization]]. > [!warning] Code not compiled in Unity > Type-checked against Unity 6000.5.8f1 assemblies, Timeline 1.8.13, Cinemachine 3.1.7 and Input System 1.20.0 (see the hub). Not compiled or run in the Editor. The skip timing below is reasoned from the package source and is exactly what part 8's play-mode test checks. The [[Timeline Basics]] controller plays, pauses and skips. A cutscene in a real game also has to **take control away and give it back**: the player must not walk off during the cutscene, the skip button must not also be the jump button, and when it ends, input, gameplay scripts and the camera must come back **once**, whether the cutscene finished, was skipped, was stopped by another system, or its GameObject was destroyed halfway. ## 6.1 The states This is the **State** pattern from [[Game Programming Patterns (Review)]] in its simplest form, an enum with guarded transitions: ``` Play() RequestSkip() Idle ──────────────► Playing ─────────────────► Skipping ▲ │ │ │ one frame later │ stopped / end │ └────────── chapter ◄────┤ (chapter skip: back to Playing) │ ▼ ▼ └──────── Finish() ◄── Finishing ◄──────── end reached (input, components and camera back; events fire once) ``` The rule that keeps it robust: **every exit goes through `Finish()`, and `Finish()` is idempotent.** `OnDisable` calls it too, so unloading the scene mid-cutscene cannot leave the player locked out. ## 6.2 Input setup In your Input Actions asset (or the project-wide actions, **Edit > Project Settings > Input System Package**): 1. Keep your gameplay map, named **Player**. 2. Add a map named **Cutscene** with one action, **Skip** (Button). Bind `<Keyboard>/escape`, `<Gamepad>/start` and `<Gamepad>/buttonEast`, or whatever your game uses for "back". 3. On **Skip**, add a **Hold** interaction (Hold Time about 0.6 s). With Hold, the action is *performed* only after the hold time, so `WasPerformedThisFrame()` means "held long enough" and an accidental tap does not skip. Only one of Player and Cutscene is enabled at a time, so the skip button cannot also trigger a gameplay action. Action maps and their consumption rules: [[Input System]] / [[2. Control Schemes Devices and Consumption Patterns]]. If players can rebind Skip ([[3. Runtime Rebinding]]), show the current binding in the prompt, as in [[Context-Sensitive Prompts and Onboarding]], and drive a radial fill from `SkipHoldProgress` (it reads `InputAction.GetTimeoutCompletionPercentage()`). **PlayerInput or not.** If the player uses a `PlayerInput` component, assign it and the controller calls `SwitchCurrentActionMap("Cutscene")`, then switches back to whatever map was current. Otherwise it disables and enables the maps on the assigned `InputActionAsset`, or on `InputSystem.actions` (the project-wide asset) if none is assigned. Do not mix: a `PlayerInput` usually works on its own copy of the actions, so disabling maps on the asset would not affect it. ## 6.3 The controller ```csharp // Assets/TimelineAdvanced/Runtime/CutsceneController.cs using System; using System.Collections.Generic; using System.Threading; using Unity.Cinemachine; using UnityEngine; using UnityEngine.Events; using UnityEngine.InputSystem; using UnityEngine.Playables; using UnityEngine.Timeline; namespace TimelineAdvanced { // Plays a cutscene and owns the hand-off: gameplay input off, cutscene input on, // optional hold-to-skip (whole cutscene or next chapter), then gameplay input, // gameplay components and the gameplay camera back, exactly once, however it ends. [RequireComponent(typeof(PlayableDirector))] public class CutsceneController : MonoBehaviour { public enum Phase { Idle, Playing, Skipping, Finishing } [Header("Input (either PlayerInput or an InputActionAsset)")] [Tooltip("If set, uses PlayerInput.SwitchCurrentActionMap. Otherwise enables/disables maps on the asset below.")] [SerializeField] PlayerInput playerInput; [Tooltip("Leave empty to use the project-wide actions (InputSystem.actions).")] [SerializeField] InputActionAsset actions; [SerializeField] string gameplayMap = "Player"; [SerializeField] string cutsceneMap = "Cutscene"; [Tooltip("An action in the Cutscene map. Give it a Hold interaction in the asset for hold-to-skip.")] [SerializeField] InputActionReference skipAction; [Header("Skip")] [SerializeField] bool allowSkip = true; [Tooltip("Skip to the next SkipPointMarker instead of the end, when one exists.")] [SerializeField] bool skipByChapter; [Header("Gameplay hand-off")] [Tooltip("Behaviours to disable while the cutscene plays: movement, interaction, CinemachineInputAxisController, HUD prompts.")] [SerializeField] List<Behaviour> disableDuringCutscene = new List<Behaviour>(); [Tooltip("The camera gameplay should return to. Prioritize() is called on it at the start, so it is the Brain's choice underneath the Timeline override.")] [SerializeField] CinemachineCamera gameplayCamera; [Header("Flow")] [SerializeField] bool playOnce = true; [Tooltip("With Wrap Mode = Hold, stop the director when the end is reached (fires 'stopped', destroys the graph). Off keeps the final frame held after control is returned.")] [SerializeField] bool stopDirectorOnFinish = true; public UnityEvent onStarted = new UnityEvent(); public UnityEvent onSkipped = new UnityEvent(); public UnityEvent onFinished = new UnityEvent(); // Global observers: pause menu, HUD, AI, music. Fired once per cutscene. public static event Action<CutsceneController> AnyStarted; public static event Action<CutsceneController> AnyFinished; public static CutsceneController Current { get; private set; } public Phase CurrentPhase { get; private set; } = Phase.Idle; public bool IsSkipping => CurrentPhase == Phase.Skipping; public bool WasSkipped { get; private set; } public PlayableDirector Director => m_Director; // 0..1 progress of a Hold interaction on the skip action, for a radial "hold to skip" UI. public float SkipHoldProgress => CurrentPhase == Phase.Playing && skipAction != null && skipAction.action != null ? skipAction.action.GetTimeoutCompletionPercentage() : 0f; PlayableDirector m_Director; bool m_HasPlayed; int m_SkipFrame; bool m_SkipToEnd; string m_PreviousPlayerInputMap; readonly List<Behaviour> m_DisabledByUs = new List<Behaviour>(); // Enter Play Mode Options can skip the domain reload; clear statics explicitly. [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)] static void ResetStatics() { Current = null; AnyStarted = null; AnyFinished = null; } void Awake() { m_Director = GetComponent<PlayableDirector>(); m_Director.playOnAwake = false; } void OnEnable() => m_Director.stopped += OnDirectorStopped; void OnDisable() { m_Director.stopped -= OnDirectorStopped; // Never leave the player locked out because the cutscene object was disabled // or its scene unloaded mid-play. if (CurrentPhase != Phase.Idle) Finish(); } public bool Play() { if (CurrentPhase != Phase.Idle || (playOnce && m_HasPlayed)) return false; if (Current != null && Current != this) { Debug.LogWarning(quot;[Cutscene] {name} ignored: {Current.name} is already playing.", this); return false; } m_HasPlayed = true; WasSkipped = false; Current = this; EnterCutsceneMode(); CurrentPhase = Phase.Playing; m_Director.time = m_Director.initialTime; m_Director.Play(); onStarted.Invoke(); AnyStarted?.Invoke(this); return true; } // Await the whole cutscene, e.g. from a boss intro or a scene loader. public async Awaitable PlayAndWaitAsync(CancellationToken cancellationToken = default) { if (!Play()) return; while (CurrentPhase != Phase.Idle) await Awaitable.NextFrameAsync(cancellationToken); } void Update() { switch (CurrentPhase) { case Phase.Playing: if (allowSkip && skipAction != null && skipAction.action != null && skipAction.action.WasPerformedThisFrame()) { RequestSkip(); } else if (m_Director.extrapolationMode == DirectorWrapMode.Hold && m_Director.time >= m_Director.duration - 1e-4) { // Hold never fires 'stopped' on its own: detect the end here. BeginFinish(); } break; case Phase.Skipping: // RequestSkip moved the playhead in Update. The director evaluates later in // the same frame (GameTime/UnscaledGameTime update after Update), firing the // markers in the skipped range. One frame later it is safe to finish. if (Time.frameCount > m_SkipFrame) { if (m_SkipToEnd) BeginFinish(); else CurrentPhase = Phase.Playing; } break; } } public void RequestSkip() { if (CurrentPhase != Phase.Playing || !allowSkip) return; double target = m_Director.duration; if (skipByChapter && TryGetNextSkipPoint(m_Director.time, out double chapterTime)) target = chapterTime; m_SkipToEnd = target >= m_Director.duration - 1e-4; WasSkipped |= m_SkipToEnd; CurrentPhase = Phase.Skipping; m_SkipFrame = Time.frameCount; // Do NOT Evaluate() here: Evaluate is treated as a scrub and never fires markers. // Setting time on a playing director lets the next evaluation fire every marker // between the old and new time (GameplayEventReceiver filters cosmetic ones). m_Director.time = target; onSkipped.Invoke(); } bool TryGetNextSkipPoint(double now, out double time) { time = double.MaxValue; if (m_Director.playableAsset is not TimelineAsset timeline) return false; Consider(timeline.markerTrack, now, ref time); foreach (TrackAsset track in timeline.GetOutputTracks()) Consider(track, now, ref time); return time < double.MaxValue; static void Consider(TrackAsset track, double current, ref double best) { if (track == null) return; foreach (IMarker marker in track.GetMarkers()) if (marker is SkipPointMarker && marker.time > current + 0.05 && marker.time < best) best = marker.time; } } void BeginFinish() { if (CurrentPhase == Phase.Idle || CurrentPhase == Phase.Finishing) return; CurrentPhase = Phase.Finishing; if (stopDirectorOnFinish && m_Director.state == PlayState.Playing) m_Director.Stop(); // raises 'stopped' synchronously -> OnDirectorStopped -> Finish else Finish(); } void OnDirectorStopped(PlayableDirector director) { // Covers Wrap Mode = None reaching the end, an external Stop(), and BeginFinish. if (CurrentPhase != Phase.Idle) Finish(); } void Finish() { if (CurrentPhase == Phase.Idle) return; CurrentPhase = Phase.Idle; ExitCutsceneMode(); if (Current == this) Current = null; onFinished.Invoke(); AnyFinished?.Invoke(this); } void EnterCutsceneMode() { if (gameplayCamera != null) gameplayCamera.Prioritize(); // make it the Brain's pick under the Timeline override m_DisabledByUs.Clear(); foreach (Behaviour b in disableDuringCutscene) { if (b != null && b.enabled) { b.enabled = false; m_DisabledByUs.Add(b); } } if (playerInput != null) { m_PreviousPlayerInputMap = playerInput.currentActionMap != null ? playerInput.currentActionMap.name : gameplayMap; playerInput.SwitchCurrentActionMap(cutsceneMap); return; } InputActionAsset asset = actions != null ? actions : InputSystem.actions; if (asset == null) return; asset.FindActionMap(gameplayMap)?.Disable(); asset.FindActionMap(cutsceneMap)?.Enable(); } void ExitCutsceneMode() { if (playerInput != null) { playerInput.SwitchCurrentActionMap(string.IsNullOrEmpty(m_PreviousPlayerInputMap) ? gameplayMap : m_PreviousPlayerInputMap); } else { InputActionAsset asset = actions != null ? actions : InputSystem.actions; if (asset != null) { asset.FindActionMap(cutsceneMap)?.Disable(); asset.FindActionMap(gameplayMap)?.Enable(); } } // Only re-enable what we disabled, so a component another system turned off stays off. foreach (Behaviour b in m_DisabledByUs) if (b != null) b.enabled = true; m_DisabledByUs.Clear(); // Camera: when the Cinemachine track stops overriding the Brain, the Brain shows // its own choice (gameplayCamera). Ease Out on the last shot = blend back; // no ease (or a skip past it) = cut back. } } } ``` ## 6.4 How the skip works, and why it waits a frame `RequestSkip()` does **not** call `Evaluate()` or `Stop()`. It sets `director.time` on the playing director and changes the phase to **Skipping**. Then: 1. Later in the same frame, the director updates (Game Time and Unscaled Game Time directors are evaluated after `Update`). That evaluation sees a forward jump and **fires every marker between the old and the new time** (part 4). 2. `GameplayEventReceiver` sees `IsSkipping == true` and drops markers with `changesGameState = false`. State events (gate open, boss awake, objective set) still run. 3. Next frame, `Update` sees `Time.frameCount > m_SkipFrame` and finishes, or, for a chapter skip, goes back to **Playing**. With **Wrap Mode = None**, the jump to `duration` makes the director finish during that evaluation and raise `stopped`, which calls `Finish()` directly. Whether `stopped` is raised before or after the last markers are delivered in that frame is **not verified**; if it comes first, `IsSkipping` is already false when a cosmetic marker arrives and it would fire. Part 8's test catches that. The fallback is to keep a `m_LastSkipFrame` and treat "skipped this frame" as skipping in the receiver. **Skip by chapter.** With `skipByChapter` on, the controller jumps to the next `SkipPointMarker` after the current time (part 4), and only a skip that reaches the end sets `WasSkipped`. Long cutscenes feel much better this way: a player who missed one line can skip the rest of a scene without losing the whole story. **When to allow skipping.** Level 17 of [[Level Up! (Review)]] says keep cutscenes short and skippable. A common compromise: `allowSkip = false` the first time, `true` once your save data says the player has seen it (the [[Boss Battles with Phases]] intro does this). That is a flag on the controller, not a second timeline. ## 6.5 Handing back the camera Read from the Cinemachine 3.1.7 docs and source (`CinemachinePlayableMixer`, `CameraBlendStack`): - While a **Cinemachine Shot** clip is active, the Cinemachine track **overrides** the Brain. Underneath, the Brain keeps choosing its own live camera by priority, as if the timeline were not there. - A shot's **Ease In** blends from the Brain's live camera into the shot. A shot's **Ease Out** blends from the shot back to the Brain's live camera. This is how you get a smooth hand-off **into and out of** gameplay. - When the override is released (the shot ends without an ease-out, or the director stops), the Brain shows its own choice **immediately**. Releasing the override creates no blend, so it is a **cut**. So the hand-off is mostly authoring, not code: 1. Put the **gameplay camera** (for example the third-person `CinemachineCamera` from [[Cinemachine 3]]) at the top priority among gameplay cameras. The controller calls `gameplayCamera.Prioritize()` at the start, so it is also the most recently prioritized among equals. During the cutscene it stays the Brain's choice underneath. 2. Give the **first** shot an Ease In if the cutscene should start with a blend from gameplay, or none for a hard cut in. 3. End the **last** shot with an **Ease Out** of about 0.5-1.5 s, finishing at or before the end of the timeline. That is the blend back. Tune the curve feel with [[5.Blends Custom Blends Cut vs Ease]]. 4. A **skip to the end** lands after the ease-out, so the override is gone: a **cut** back to gameplay, which is what a player who pressed Skip wants. If you need different behaviour (always blend, even on skip), the general hook is `CinemachineCore.GetBlendOverride`, a static delegate called whenever a Cinemachine blend is created. It is not used here because releasing a Timeline override does not create a blend. **Gameplay camera input.** A `CinemachineInputAxisController` (orbit/look input) reads its own Input Action references and, with **Auto Enable Inputs** on, enables those actions once when it first resolves them. Add it to `disableDuringCutscene` so the camera rig does not drift during the cutscene, whatever the action-map state. ## 6.6 Handing back the player - Add the player's **movement**, **interaction**, **combat** and **prompt** components to `disableDuringCutscene`. The controller only re-enables what it disabled, so a component that another system turned off stays off. - If an **Animation track moved the player**, the Animator returns to its own controller when the track stops. A `CharacterController` or `Rigidbody` may then disagree with the transform. Prefer ending the cutscene with the player where gameplay expects them (author the last frame there), or teleport explicitly in `onFinished`. With a `CharacterController`, disable it, set the position and re-enable it, or the next `Move` can undo the teleport. - Use `onFinished` (or `AnyFinished`) to restore HUD, music state and objective prompts. Keep that logic in the systems that own it. ## 6.7 Using it 1. On the cutscene object: PlayableDirector (Play On Awake off, Wrap Mode **None**), `CutsceneController`, `GameplayEventReceiver`. 2. Assign the Input Actions asset (or `PlayerInput`), the **Skip** action reference, the gameplay `CinemachineCamera` and the behaviours to disable. 3. Trigger it from gameplay: a trigger volume calling `controller.Play()`, or `await controller.PlayAndWaitAsync(destroyCancellationToken)` in a level script. 4. Play it through, then play it again (with `playOnce` off) and hold Skip halfway. Check: input works, the camera is the gameplay camera, the gate is open, the shake did not fire. ## 6.8 Exercise Add an `InteractiveDialogue` phase: on a `dialogue.choice` marker (part 3), call `director.Pause()`, switch to a **UI** action map, and resume with `director.Resume()` and the Cutscene map when the dialogue closes. Make sure `Finish()` from any phase still restores the **Player** map. ## Sources - `PlayableDirector` (6000.5): https://docs.unity3d.com/6000.5/Documentation/ScriptReference/Playables.PlayableDirector.html - Input System `InputAction` (`WasPerformedThisFrame`, `GetTimeoutCompletionPercentage`) (1.20): https://docs.unity3d.com/Packages/[email protected]/api/UnityEngine.InputSystem.InputAction.html - Input System interactions (Hold): https://docs.unity3d.com/Packages/[email protected]/manual/Interactions.html - Cinemachine and Timeline (3.1): https://docs.unity3d.com/Packages/[email protected]/manual/concept-timeline.html - Cinemachine camera control and transitions (3.1): https://docs.unity3d.com/Packages/[email protected]/manual/concept-camera-control-transitions.html - `CinemachineCore` (`GetBlendOverride`) (3.1): https://docs.unity3d.com/Packages/[email protected]/api/Unity.Cinemachine.CinemachineCore.html - Package source: Cinemachine 3.1.7 `Runtime/Timeline/CinemachinePlayableMixer.cs`, `Runtime/Core/CameraBlendStack.cs`, `Runtime/Helpers/CinemachineInputAxisController.cs` (Unity package registry). - State chapter: https://gameprogrammingpatterns.com/state.html