# 8. Worked Example Tests and Pitfalls Part of [[Timeline Advanced]]. Previous: [[7. Timeline Editor Customization]]. > [!warning] Code not compiled in Unity > The test was type-checked against Unity 6000.5.8f1 assemblies, Timeline 1.8.13, Input System 1.20.0, the Unity Test Framework runtime and NUnit (see the hub). It has **not been run**. Treat its first run as the real verification of the skip behaviour in parts 4 and 6. ## 8.1 "Gate Briefing": the scene A guard briefs the player at a town gate, the gate opens, and control returns with the camera blending back behind the player. About 20 seconds, which is the length Level 17 of [[Level Up! (Review)]] suggests for a first skippable intro. **Scene objects** - `Player` with movement and interaction scripts, a third-person `CinemachineCamera` (`CM_Gameplay`) with a `CinemachineInputAxisController`. Main Camera with a `CinemachineBrain`. - `Guard` with an Animator. - `Gate` with a component that has `Open()` (sets its open pose and collider state itself). - `GateLamp`, a realtime Point Light. - `Subtitles` (UIDocument + `SubtitleView`, part 3). - Two shot cameras: `CM_Wide` (gate and guard) and `CM_Close` (guard's face). - `Cutscene_GateBriefing`: PlayableDirector (Play On Awake off, Wrap Mode **None**, Update **Game Time**), `CutsceneController`, `GameplayEventReceiver` (onEvent → `GateEvents.Handle(id, value)`), a trigger `BoxCollider` and a tiny trigger script that calls `controller.Play()` when the player enters. **Timeline `GateBriefing.playable`** | Track | Binding | Content | |---|---|---| | Cinemachine Track | Main Camera (Brain) | `CM_Wide` 0-6 s (Ease In 1 s: blend in from gameplay), `CM_Close` 5.5-14 s (overlap = blend), `CM_Wide` 13.5-20 s with **Ease Out 1.5 s** ending at 20 s | | Animation Track | Guard | talk loop 0-14 s, point at gate 14-17 s | | Subtitle Track | Subtitles | 4 lines, each 3-4 s, Ease In/Out 0.2 s, 0.2 s overlaps | | Audio Track | (none, 2D) | 4 VO clips aligned to the subtitles | | Light Intensity Track | GateLamp | swell clip 14-18 s (curve 0 → 1, intensity 5), `restoreOnStop` **off** | | Markers row | (director) | `SkipPoint` at 9 s ("Second half"), `GameplayEvent gate.open` at 16 s (state, Retroactive), `GameplayEvent camera.shake` at 16.1 s (cosmetic, not Retroactive) | **Flow** 1. The player enters the trigger → `Play()` → Player map off, Cutscene map on, movement, interaction and `CinemachineInputAxisController` disabled, `CM_Gameplay.Prioritize()`. 2. The first shot eases in from the gameplay camera. Subtitles and VO play. The lamp swells as the gate opens at 16 s; `gate.open` calls `Gate.Open()`; `camera.shake` triggers an Impulse ([[Combat Feel and Hit Feedback]]; respect [[4. Reduced Motion]]). 3. The last shot eases out from 18.5 s to 20 s, blending back to `CM_Gameplay`. At 20 s the None-wrap director stops → `Finish()` → Player map, components and HUD back. 4. **Hold Skip at 4 s** with `skipByChapter` on → jump to 9 s. **Hold Skip again** → jump to 20 s: `gate.open` fires (state), `camera.shake` is dropped (cosmetic), the camera **cuts** to gameplay, the lamp keeps its swelled value (`restoreOnStop` off), and the gate is open because `Gate.Open()` sets its own pose. **Check list after each run (natural end, chapter skip, full skip, and quitting to the menu mid-cutscene):** - the player can move and look, - the camera is `CM_Gameplay`, - the gate is open and passable (except after quitting), - `gate.open` ran exactly once, - no cosmetic events fired on the skipped run, - the subtitle box is hidden. ## 8.2 The play-mode test The test builds everything in code: an `InputActionAsset` with Player and Cutscene maps, a one-second `TimelineAsset` with a state marker and a cosmetic marker on the Markers row, and a director with the controller and receiver. It plays, skips, and asserts. Test assemblies and fixtures are covered in [[Unity Test Framework]] / [[4. Play Mode Tests and Scene Fixtures]]. `Assets/TimelineAdvanced/Tests/PlayMode/TimelineAdvanced.Tests.asmdef`: ```json { "name": "TimelineAdvanced.Tests", "references": [ "TimelineAdvanced", "Unity.Timeline", "Unity.InputSystem", "Unity.Cinemachine", "UnityEngine.TestRunner", "UnityEditor.TestRunner" ], "overrideReferences": true, "precompiledReferences": [ "nunit.framework.dll" ], "defineConstraints": [ "UNITY_INCLUDE_TESTS" ] } ``` ```csharp // Assets/TimelineAdvanced/Tests/PlayMode/CutsceneControllerTests.cs // PlayMode test assembly referencing: TimelineAdvanced (runtime asmdef), Unity.Timeline, // Unity.InputSystem, Unity.Cinemachine, UnityEngine.TestRunner, nunit.framework. using System.Collections; using NUnit.Framework; using UnityEngine; using UnityEngine.InputSystem; using UnityEngine.Playables; using UnityEngine.TestTools; using UnityEngine.Timeline; namespace TimelineAdvanced.Tests { public class CutsceneControllerTests { GameObject m_Root; TimelineAsset m_Timeline; InputActionAsset m_Actions; [SetUp] public void SetUp() { // Input: a Player map and a Cutscene map, built in code. m_Actions = ScriptableObject.CreateInstance<InputActionAsset>(); m_Actions.AddActionMap("Player").AddAction("Move", InputActionType.Value); m_Actions.AddActionMap("Cutscene").AddAction("Skip", InputActionType.Button); m_Actions.FindActionMap("Player").Enable(); // Timeline: 1 s long, one state marker at 0.5 s and one cosmetic marker at 0.6 s. m_Timeline = ScriptableObject.CreateInstance<TimelineAsset>(); m_Timeline.CreateMarkerTrack(); var state = m_Timeline.markerTrack.CreateMarker<GameplayEventMarker>(0.5); state.eventId = "gate.open"; state.changesGameState = true; var cosmetic = m_Timeline.markerTrack.CreateMarker<GameplayEventMarker>(0.6); cosmetic.eventId = "camera.shake"; cosmetic.changesGameState = false; var probe = m_Timeline.CreateTrack<LifecycleProbeTrack>(null, "Probe"); probe.CreateClip<LifecycleProbeClip>().duration = 1.0; m_Root = new GameObject("Cutscene"); m_Root.SetActive(false); // configure before Awake/OnEnable run var director = m_Root.AddComponent<PlayableDirector>(); director.playableAsset = m_Timeline; director.extrapolationMode = DirectorWrapMode.None; m_Root.AddComponent<GameplayEventReceiver>(); var controller = m_Root.AddComponent<CutsceneController>(); SetPrivate(controller, "actions", m_Actions); SetPrivate(controller, "playOnce", false); } [TearDown] public void TearDown() { Object.Destroy(m_Root); Object.Destroy(m_Timeline); Object.Destroy(m_Actions); } [UnityTest] public IEnumerator Skip_RestoresGameplayInput_AndKeepsOnlyStateEvents() { var fired = new System.Collections.Generic.List<string>(); void Record(string id, float value) => fired.Add(id); GameplayEventReceiver.AnyGameplayEvent += Record; m_Root.SetActive(true); var controller = m_Root.GetComponent<CutsceneController>(); Assert.IsTrue(controller.Play()); Assert.IsFalse(m_Actions.FindActionMap("Player").enabled, "Player map should be off during the cutscene"); Assert.IsTrue(m_Actions.FindActionMap("Cutscene").enabled); yield return null; // let it start controller.RequestSkip(); yield return null; // director evaluates the jump yield return null; // controller finishes GameplayEventReceiver.AnyGameplayEvent -= Record; Assert.AreEqual(CutsceneController.Phase.Idle, controller.CurrentPhase); Assert.IsTrue(controller.WasSkipped); Assert.IsTrue(m_Actions.FindActionMap("Player").enabled, "Player map should be back on"); Assert.IsFalse(m_Actions.FindActionMap("Cutscene").enabled); CollectionAssert.Contains(fired, "gate.open"); CollectionAssert.DoesNotContain(fired, "camera.shake"); } static void SetPrivate(object target, string field, object value) { var info = target.GetType().GetField(field, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); Assert.IsNotNull(info, quot;field {field}"); info.SetValue(target, value); } } } ``` Notes: - The GameObject is created **inactive** so the private fields can be set (by reflection) before `Awake` and `OnEnable` run. In your own project, prefer making those fields settable through a small `Configure(...)` method, or test against a prefab. - The three `yield return null` lines are the timing from part 6: one frame to start, one for the director to evaluate the jump, one for the controller to finish. If the test fails only on `DoesNotContain("camera.shake")`, the director raised `stopped` before delivering the last markers; apply the "skipped this frame" fallback from part 6.4. - Run it from **Window > General > Test Runner > PlayMode**. ## 8.3 Pitfalls | Symptom | Likely cause | Fix | |---|---|---| | Custom track missing from the **+** menu | Compile error, class name does not match file name, or missing `[TrackClipType]` | Fix the console; one class per file; Timeline 1.8.9+ warns about name mismatch | | Clips cannot ease or blend | `clipCaps` lacks `Blending` | Return `ClipCaps.Blending` (and only what the mixer supports) | | Light jumps to black at clip edges | Mixer blends toward zero, not toward scene values | Capture defaults from the binding and add `default * (1 - totalWeight)` (part 2) | | Scene dirty after scrubbing a custom track | No `GatherProperties` | Register the serialized fields the mixer writes (part 2) | | Values stuck after the cutscene | No restore in `OnPlayableDestroy`, or Wrap Mode Hold never stopped | Restore in the mixer; use None or `stopDirectorOnFinish` | | Marker never fires | Receiver on the wrong object | Markers row → director's GameObject; track marker → the track's bound GameObject (part 4.1) | | Markers in the skipped range never fire | Skip used `Evaluate()` (a scrub) | Set `time` on the playing director and let it evaluate (part 6.4) | | Ten cosmetic effects fire at once on skip | Forward jump fires everything in range | Mark cosmetic markers `changesGameState = false` (part 4.5) | | Soft-lock after skip: gate shut | Gate state only lived in the Animation track | Make the state event set real state; Retroactive on (part 4.5) | | Camera stuck on a cutscene shot | Wrap Mode Hold with a shot still active on the last frame | End the last shot with an Ease Out before the end, or stop the director | | Camera cuts back when you wanted a blend | No Ease Out on the last shot | Add Ease Out; the override release itself never blends (part 6.5) | | Camera blends to the wrong gameplay camera | Another camera has higher priority under the override | Set priorities; `gameplayCamera.Prioritize()` (part 6.5) | | Player walks off during the cutscene | Gameplay map still enabled, or `PlayerInput` copy unaffected | Use the `PlayerInput` path when there is a PlayerInput; disable movement components too | | Camera drifts during the cutscene | `CinemachineInputAxisController` still reading input | Add it to `disableDuringCutscene` | | Player snaps back after the cutscene | CharacterController and Animator disagree with the transform | End where gameplay expects, or teleport with the CharacterController disabled (part 6.6) | | Player locked after loading a scene mid-cutscene | Finish never ran | `OnDisable` calls `Finish()`; keep that | | Static events fire twice after re-entering Play Mode | Enter Play Mode Options without domain reload | Reset statics with `RuntimeInitializeOnLoadMethod(SubsystemRegistration)` | | Bindings ignored after `SetGenericBinding` | Graph already built | `RebuildGraph()` (part 5) | | VO keeps playing in the pause menu | Relying on `timeScale = 0` | `director.Pause()` from the pause flow (part 5.3) | | Subtitles not shown | `UIDocument` element names differ from `SubtitleView` fields, or Panel Settings missing | Match names; assign Panel Settings | ## 8.4 Where to use this next - [[Boss Battles with Phases]] / [[4. Timeline Intros and Phase Transitions]]: replace its intro control code with `await intro.PlayAndWaitAsync(...)`, and mark "boss.awake" as a state event. - [[Capstone 3D Platformer Vertical Slice]], [[Stealth Game Capstone]] and [[2D Platformer Capstone]]: an intro and an outro per level, skippable on replay. - [[VR Capstone Game for Quest 2]]: in VR, do not take the camera away. Keep head tracking, use the subtitle track on a world-space view and fade instead of cutting. - Performance of large cutscenes (many tracks, Animation tracks on crowds): profile with [[Profiling and Optimization]]; Timeline 1.8.9 added profiler markers for graph creation and evaluation. ## Sources - Unity Test Framework (play-mode tests, `UnityTest`): https://docs.unity3d.com/Packages/[email protected]/manual/index.html - `TimelineAsset` (`CreateTrack`, `CreateMarkerTrack`, `markerTrack`) (Timeline 1.8): https://docs.unity3d.com/Packages/[email protected]/api/UnityEngine.Timeline.TimelineAsset.html - Input System `InputActionSetupExtensions` (`AddActionMap`, `AddAction`) (1.20): https://docs.unity3d.com/Packages/[email protected]/api/UnityEngine.InputSystem.InputActionSetupExtensions.html - Timeline 1.8 changelog (name-mismatch warning, profiler markers): https://docs.unity3d.com/Packages/[email protected]/changelog/CHANGELOG.html - Cinemachine and Timeline (3.1): https://docs.unity3d.com/Packages/[email protected]/manual/concept-timeline.html