# 1. Playables Mental Model and Clip Lifecycle Part of [[Timeline Advanced]]. Next: [[2. Custom Light Intensity Track with a Mixer]]. > [!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. [[Timeline Basics]] section 6 wrote a fade track as "three classes". This part explains what those three classes turn into, so the custom tracks in parts 2 and 3 are not cargo cult. ## 1.1 What Timeline builds A **TimelineAsset** is data. When a **PlayableDirector** plays it (or you scrub in the Timeline window), the director builds a **PlayableGraph**: ``` PlayableGraph (owned by the PlayableDirector) └─ TimelinePlayable (root) ← time, speed, wrap mode ├─ Track mixer (CreateTrackMixer → ScriptPlayable<YourMixer>) │ ├─ input 0: clip playable (CreatePlayable → ScriptPlayable<YourBehaviour>) weight 0..1 │ ├─ input 1: clip playable weight 0..1 │ └─ ... └─ ... one subtree per track Outputs: one PlayableOutput per track → the bound object (Light, Animator, AudioSource, your component) ``` - **One output per track.** The object you drag into the track's binding slot is the output's target. In your behaviour it arrives as `playerData` in `ProcessFrame`, typed as `object`. - **One mixer per track.** Timeline connects every clip of the track as an input and sets each input's **weight** every frame from the clip's start, end, ease-in/out and overlaps. Without a custom mixer, Timeline uses a plain one and each clip behaviour runs on its own; you cannot blend. - **One playable per clip.** Your `PlayableAsset.CreatePlayable` runs once per clip when the graph is built, not every frame. - **The graph is rebuilt**, and every behaviour recreated, when playback starts after a stop, when you call `RebuildGraph()`, and (in the editor) when you edit the timeline. Per-graph state lives in the behaviour; anything that must survive belongs on a component. ## 1.2 The three classes | Class | Lives in | Job | |---|---|---| | `PlayableAsset` (+ `ITimelineClipAsset`) | the `.playable` asset, one per clip | Serialized clip settings; `CreatePlayable` makes the runtime playable; `clipCaps` says what the clip supports | | `PlayableBehaviour` | runtime only, inside the graph | Per-clip logic (or per-track logic, as the mixer) | | `TrackAsset` | the `.playable` asset, one per track | Which clip types it accepts, what it binds to, its colour, and its mixer | The usual pattern is a **template**: the clip asset holds a serializable behaviour instance, and `ScriptPlayable<T>.Create(graph, template)` clones it, so each clip gets its own copy of the values at graph build time. Attributes on the track: - `[TrackClipType(typeof(MyClip))]` - which clip assets this track accepts (repeatable). - `[TrackBindingType(typeof(Light))]` - the binding slot type. Omit it for a track that needs no scene object; `playerData` is then null. - `[TrackColor(r, g, b)]` - the colour stripe in the Timeline window. - `[System.ComponentModel.DisplayName("Folder/Name")]` - the name and sub-menu in the Timeline **+** menu. Timeline 1.8.13 fixed context-menu handling of `/` in these names. ## 1.3 ClipCaps `ITimelineClipAsset.clipCaps` turns clip inspector features on: | Flag | Gives the clip | |---|---| | `None` | Nothing extra: position and length only | | `Looping` | Loop option for clips whose content is shorter than the clip | | `Extrapolation` | Pre/Post-Extrapolate (Hold, Loop, Ping Pong, Continue) into gaps | | `ClipIn` | A Clip In offset (start part-way into the content) | | `SpeedMultiplier` | A Speed Multiplier for local time | | `Blending` | Ease In/Out durations and blends on overlap, which become **input weights** | | `AutoScale` | Scaling the clip scales its speed (implies `SpeedMultiplier`) | | `All` | Everything | Only claim what your mixer handles. A clip with `Blending` but a mixer that ignores weights looks broken. ## 1.4 PlayableBehaviour callbacks | Callback | When | Use it for | |---|---|---| | `OnPlayableCreate` | the playable is created | rarely needed; the template is already copied | | `OnGraphStart` | the graph starts playing (also after Resume or a rebuild) | caching, resetting per-run state | | `OnBehaviourPlay` | the playable becomes active: the playhead enters the clip, or the director plays | one-shot "start" logic | | `PrepareFrame` | each evaluation, before `ProcessFrame`; inputs first | timing logic that does not touch the binding | | `ProcessFrame` | each evaluation, with `playerData` = the binding | **writing to the bound object** | | `OnBehaviourPause` | the playable stops being active: the playhead leaves the clip, the director pauses or stops | one-shot "end" logic | | `OnGraphStop` | the graph stops | | | `OnPlayableDestroy` | the graph is destroyed (Stop, end of a None-wrap timeline, rebuild) | **restoring the binding's original values** | Two consequences you will hit: - `OnBehaviourPause` is not only "the clip ended". It also runs when the whole director pauses or stops. If you need "the playhead passed the end of this clip", check the clip's local time against its duration in the mixer, or put a marker there. - In the mixer, `ProcessFrame` runs every evaluated frame for the track, whether a clip is under the playhead or not. That is where gaps are handled: weight 0 everywhere means "show the scene's own value". `FrameData` (the `info` parameter) carries `deltaTime`, `weight`, `effectiveWeight`, `effectivePlayState`, `evaluationType` (`Playback` versus `Evaluate`, a scrub), `seekOccurred`, `timeLooped` and `output`. The probe below logs them so you can see the difference between playing, scrubbing and skipping. ## 1.5 Scene objects from an asset: ExposedReference A clip lives in an asset, so it cannot serialize a direct reference to a scene object. `ExposedReference<T>` stores an id in the asset; the **PlayableDirector** stores the object for that id in its own reference table. At graph build time you resolve it with `graph.GetResolver()` (the director). Each director that plays the same timeline can point the same clip at different scene objects. Part 5 sets these from code with `SetReferenceValue`. ## 1.6 The lifecycle probe Three small scripts: a behaviour that logs every callback, a clip with an `ExposedReference<Transform>`, and a track with no binding. ```csharp // Assets/TimelineAdvanced/Runtime/LifecycleProbeBehaviour.cs using System; using UnityEngine; using UnityEngine.Playables; namespace TimelineAdvanced { // Logs every PlayableBehaviour callback so you can see the clip lifecycle // (play, pause, scrub, skip, stop) for yourself. Delete it once you trust the model. [Serializable] public class LifecycleProbeBehaviour : PlayableBehaviour { public string label = "Probe"; public bool logEveryFrame; // Runtime-only: resolved from the clip's ExposedReference when the graph is built. [NonSerialized] public Transform target; public override void OnGraphStart(Playable playable) => Log("OnGraphStart", playable); public override void OnGraphStop(Playable playable) => Log("OnGraphStop", playable); public override void OnBehaviourPlay(Playable playable, FrameData info) => Log(quot;OnBehaviourPlay evaluationType={info.evaluationType} seekOccurred={info.seekOccurred}", playable); public override void OnBehaviourPause(Playable playable, FrameData info) => Log(quot;OnBehaviourPause effectivePlayState={info.effectivePlayState} effectiveWeight={info.effectiveWeight:0.00}", playable); public override void PrepareFrame(Playable playable, FrameData info) { if (logEveryFrame) Log(quot;PrepareFrame deltaTime={info.deltaTime:0.0000} weight={info.weight:0.00} timeLooped={info.timeLooped}", playable); } public override void ProcessFrame(Playable playable, FrameData info, object playerData) { if (logEveryFrame) Log(quot;ProcessFrame playerData={(playerData == null ? "null" : playerData.ToString())}", playable); } public override void OnPlayableDestroy(Playable playable) => Log("OnPlayableDestroy", playable); void Log(string evt, Playable playable) { string targetName = target != null ? target.name : "none"; Debug.Log(quot;[{label}] {evt} local={playable.GetTime():0.000}/{playable.GetDuration():0.000} target={targetName}"); } } } ``` ```csharp // Assets/TimelineAdvanced/Runtime/LifecycleProbeClip.cs using System; using UnityEngine; using UnityEngine.Playables; using UnityEngine.Timeline; namespace TimelineAdvanced { [Serializable] public class LifecycleProbeClip : PlayableAsset, ITimelineClipAsset { public LifecycleProbeBehaviour template = new LifecycleProbeBehaviour(); // A scene object referenced from an asset. The PlayableDirector stores the actual // object in its reference table (Inspector: the clip field shows the scene object). public ExposedReference<Transform> target; // No blending, no clip-in, no speed: the simplest possible clip. public ClipCaps clipCaps => ClipCaps.None; // Default length of a newly created clip, in seconds. public override double duration => 2.0; public override Playable CreatePlayable(PlayableGraph graph, GameObject owner) { var playable = ScriptPlayable<LifecycleProbeBehaviour>.Create(graph, template); playable.GetBehaviour().target = target.Resolve(graph.GetResolver()); return playable; } } } ``` ```csharp // Assets/TimelineAdvanced/Runtime/LifecycleProbeTrack.cs using System.ComponentModel; using UnityEngine.Timeline; namespace TimelineAdvanced { // No TrackBindingType: the track needs no scene object, so playerData is null. // The DisplayName path groups it under "Timeline Advanced" in the + menu. [TrackColor(0.85f, 0.85f, 0.25f)] [TrackClipType(typeof(LifecycleProbeClip))] [DisplayName("Timeline Advanced/Lifecycle Probe Track")] public class LifecycleProbeTrack : TrackAsset { } } ``` **Try it:** 1. In any timeline (the door cutscene from [[Timeline Basics]] is fine), **+ > Timeline Advanced > Lifecycle Probe Track**. 2. Add two probe clips with a gap between them. Name the labels `A` and `B`; drag a scene object into `A`'s **Target** field. 3. Enter Play Mode and play the director. Watch the order: `OnGraphStart`, `OnBehaviourPlay` for A, `OnBehaviourPause` when the playhead leaves A, and so on. 4. Pause the director: every active probe logs `OnBehaviourPause`. Resume: expect `OnGraphStart` and `OnBehaviourPlay` again (the Timeline source treats a resume as a graph start; confirm in your log). 5. In Edit Mode, scrub: `evaluationType` is `Evaluate`, not `Playback`. That flag is why markers do not fire on scrub (part 4). 6. Stop: `OnPlayableDestroy` for every clip. That is where part 2's mixer restores the light. Delete the probe track once you have seen it. The `logEveryFrame` option is very noisy. ## 1.7 Exercise Duplicate the director GameObject so two directors play the same timeline. Point clip A's Target at a different object on each. Confirm that each director logs its own target: the asset is shared, the references are per director. ## Sources - `PlayableBehaviour` (6000.5): https://docs.unity3d.com/6000.5/Documentation/ScriptReference/Playables.PlayableBehaviour.html - `ScriptPlayable<T>` (6000.5): https://docs.unity3d.com/6000.5/Documentation/ScriptReference/Playables.ScriptPlayable_1.html - `FrameData` (6000.5): https://docs.unity3d.com/6000.5/Documentation/ScriptReference/Playables.FrameData.html - `ExposedReference<T>` (6000.5): https://docs.unity3d.com/6000.5/Documentation/ScriptReference/ExposedReference_1.html - `ClipCaps` (Timeline 1.8): https://docs.unity3d.com/Packages/[email protected]/api/UnityEngine.Timeline.ClipCaps.html - `TrackAsset` (Timeline 1.8): https://docs.unity3d.com/Packages/[email protected]/api/UnityEngine.Timeline.TrackAsset.html - Timeline 1.8 changelog: https://docs.unity3d.com/Packages/[email protected]/changelog/CHANGELOG.html