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