# 4. Signals and Custom Markers Part of [[Timeline Advanced]]. Previous: [[3. Subtitle and Dialogue Track]]. Next: [[5. PlayableDirector Control and Runtime Binding]]. > [!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 4 placed a Signal and a simple `DialogueMarker`. This part is about the part that bites later: **when exactly markers fire**, especially when the player skips, and how to make a skip leave the world in the right state. Markers are the **Observer** pattern from [[Game Programming Patterns (Review)]]: the timeline (subject) announces "this moment happened" and does not know who listens. The usual Observer warnings apply: unsubscribe from static events in `OnDisable` (the "lapsed listener" problem), and keep handlers cheap. ## 4.1 The three pieces, and where receivers must live | Piece | What it is | |---|---| | **Marker** | A point in time on a track's marker area or on the timeline's **Markers** row. `SignalEmitter` is a marker; so is anything deriving from `Marker`. | | **Notification** | A marker that implements `INotification` is *pushed* to receivers when it fires. A marker without it (like `SkipPointMarker` below) is just data. | | **Receiver** | A component implementing `INotificationReceiver`. `SignalReceiver` is one: it maps a `SignalAsset` to a `UnityEvent`. | Where the receiver must be: - Marker on the **Markers row** (top of the timeline): receivers on the **PlayableDirector's GameObject**. In the 1.8.13 source, `TimelinePlayable` adds every `INotificationReceiver` on the director's GameObject to the marker track's output. - Marker on a **track**: receivers on the **GameObject bound to that track**. The docs describe this for GameObject bindings. For a Component binding (an `Animator`, a `SubtitleView`) the receiver should go on that component's GameObject; this case was not verified separately. - Signal track: a Signal track's binding *is* the receiver's GameObject; Unity offers to add a `SignalReceiver` when you bind it. If a marker "does nothing", check this first. ## 4.2 When markers fire Read from `TimeNotificationBehaviour` in the Timeline 1.8.13 package source: | Situation | What fires | |---|---| | Normal playback | Each frame, every marker between the previous frame's time and the current time. | | **Scrub or `PlayableDirector.Evaluate()`** | **Nothing.** An `Evaluate` evaluation is treated as a scrub and returns before firing. | | Playback **starts** part-way (`time = 5; Play()`) | Markers before 5 s fire only if they are **Retroactive**. | | `director.time` jumps **forward** while playing | On the next evaluation, **every marker in the skipped range** fires, Retroactive or not. | | `director.time` jumps **backward** | Markers after the new time are re-armed, so they fire again (unless **Emit Once**). | | Loop wrap | Markers re-arm each loop unless **Emit Once**. | | A None-wrap timeline reaches its end | Unfired markers up to the end fire as it finishes. | | Edit Mode | Only markers with **Trigger In Edit Mode** (`NotificationFlags.TriggerInEditMode`). | So the [[Timeline Basics]] skip (`time = duration; Evaluate(); Stop()`) does **not** fire the markers it skips, because `Evaluate` never fires and `Stop` tears the graph down. Part 6 instead moves the playhead on the playing director and lets one evaluation happen, which fires everything in the skipped range. That raises the real design question. **Which skipped events should still happen?** - **State events** change the world: open the gate, wake the boss, set the objective, give the key. They **must** run on a skip, or the player is soft-locked. - **Cosmetic events** are moments: a camera shake, a voice bark, a rumble, a particle burst. Firing ten of them in one frame on a skip is noise at best. The marker below carries that choice as data, and its receiver drops cosmetic events while the cutscene controller is skipping. ## 4.3 Signals in depth Signals (`SignalAsset` + `SignalEmitter` + `SignalReceiver`) are the no-code version: one asset per event name, reactions as UnityEvents in the Inspector. - The emitter's **Retroactive** and **Emit Once** checkboxes are the same `NotificationFlags` the custom marker uses. - A **SignalReceiver can react to many SignalAssets**; one per Signal track binding is usual. - Reactions are serialized in the scene, not in the timeline. That is the main limitation for **prefab cutscenes**: the prefab cannot point at scene-only objects. The fix is to register reactions in code. ```csharp // Assets/TimelineAdvanced/Runtime/SignalReactionBinder.cs using UnityEngine; using UnityEngine.Events; using UnityEngine.Timeline; namespace TimelineAdvanced { // Wires SignalReceiver reactions from code instead of the Inspector, so a prefab // cutscene can be dropped into any scene and still reach scene-only systems. [RequireComponent(typeof(SignalReceiver))] public class SignalReactionBinder : MonoBehaviour { [SerializeField] SignalAsset gateOpened; [SerializeField] SignalAsset cutsceneOutro; SignalReceiver m_Receiver; void Awake() { m_Receiver = GetComponent<SignalReceiver>(); AddListener(gateOpened, OnGateOpened); AddListener(cutsceneOutro, OnOutro); } void AddListener(SignalAsset signal, UnityAction action) { if (signal == null) return; // AddReaction throws if the SignalAsset is already registered (for example from // the Inspector), so append to the existing UnityEvent in that case. UnityEvent existing = m_Receiver.GetReaction(signal); if (existing != null) { existing.AddListener(action); return; } var reaction = new UnityEvent(); reaction.AddListener(action); m_Receiver.AddReaction(signal, reaction); } void OnGateOpened() => Debug.Log("Signal: gate opened"); void OnOutro() => Debug.Log("Signal: outro started"); } } ``` `SignalReceiver.AddReaction` throws an `ArgumentException` if that SignalAsset is already registered (from the Inspector, for example), so the binder appends to the existing event instead. ## 4.4 A marker that carries data `SignalEmitter` only carries "which SignalAsset". For anything more (an id, a value, a flag) write a marker. Implementing `INotificationOptionProvider` gives your marker the same Retroactive / Emit Once / Edit Mode behaviour; the Timeline source reads the `flags` property from any marker that implements it. ```csharp // Assets/TimelineAdvanced/Runtime/GameplayEventMarker.cs using System; using System.ComponentModel; using UnityEngine; using UnityEngine.Playables; using UnityEngine.Timeline; namespace TimelineAdvanced { // A marker that carries data (unlike a SignalEmitter, which only points at a SignalAsset). // INotification makes Timeline push it to receivers; INotificationOptionProvider gives // it the same Retroactive / Emit Once / Edit Mode options a SignalEmitter has. [Serializable] [DisplayName("Timeline Advanced/Gameplay Event")] public class GameplayEventMarker : Marker, INotification, INotificationOptionProvider { static readonly PropertyName k_Id = new PropertyName("TimelineAdvanced.GameplayEvent"); [Tooltip("What happened, e.g. gate.open, boss.awake, objective.set")] public string eventId = "gate.open"; public float value; [Tooltip("State events change the world (open a gate, set an objective) and must still fire when the player skips. Cosmetic events (camera shake, a VO bark) should not.")] public bool changesGameState = true; [SerializeField] bool retroactive = true; [SerializeField] bool emitOnce; [SerializeField] bool emitInEditMode; public PropertyName id => k_Id; public NotificationFlags flags => (retroactive ? NotificationFlags.Retroactive : default) | (emitOnce ? NotificationFlags.TriggerOnce : default) | (emitInEditMode ? NotificationFlags.TriggerInEditMode : default); } } ``` - `id` identifies the notification type. Every instance returns the same id here; receivers switch on the C# type and `eventId` instead. - `retroactive` defaults to **true** for this marker: a gameplay event that a late start skipped over usually still needs to happen. Turn it off for cosmetic events. - Right-click a track's marker area or the Markers row: **Add Timeline Advanced/Gameplay Event** (the `DisplayName` sets the menu path). If the menu path does not appear exactly like that in your version, look for "Gameplay Event Marker" in the marker context menu. ## 4.5 A skip-aware receiver ```csharp // Assets/TimelineAdvanced/Runtime/GameplayEventReceiver.cs using System; using UnityEngine; using UnityEngine.Events; using UnityEngine.Playables; namespace TimelineAdvanced { // Put this on the GameObject a track is bound to (for markers on that track), // or on the PlayableDirector's GameObject (for markers on the Markers row). public class GameplayEventReceiver : MonoBehaviour, INotificationReceiver { [Serializable] public class GameplayEvent : UnityEvent<string, float> { } [Tooltip("Only react to this id. Leave empty to react to every GameplayEventMarker.")] public string filterId = ""; public GameplayEvent onEvent = new GameplayEvent(); // Code-side observers (Observer pattern): quest system, analytics, audio. public static event Action<string, float> AnyGameplayEvent; [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)] static void ResetStatics() => AnyGameplayEvent = null; public void OnNotify(Playable origin, INotification notification, object context) { if (notification is not GameplayEventMarker marker) return; if (!string.IsNullOrEmpty(filterId) && marker.eventId != filterId) return; // During a skip, every marker between the old time and the new time fires on the // next evaluation. Let state events through and drop cosmetic ones. var director = origin.IsValid() ? origin.GetGraph().GetResolver() as PlayableDirector : null; if (director != null && director.TryGetComponent(out CutsceneController controller) && controller.IsSkipping && !marker.changesGameState) return; onEvent.Invoke(marker.eventId, marker.value); AnyGameplayEvent?.Invoke(marker.eventId, marker.value); } } } ``` - `origin.GetGraph().GetResolver()` is the PlayableDirector that owns the graph, so the receiver can ask that director's `CutsceneController` (part 6) whether it is skipping. A receiver on another object still finds the right controller. - `AnyGameplayEvent` is a static C# event for code-side listeners (quest system, analytics, music). The `RuntimeInitializeOnLoadMethod` reset matters if you use **Enter Play Mode Options** without a domain reload; otherwise listeners from the last Play session survive. - If several receivers sit on the same GameObject, each gets every notification. Use `filterId` to split them. **Hooking it to gameplay.** Keep the receiver thin: forward `eventId` to the system that owns the state. For example, the gate's own component listens for `gate.open` and sets its "open" flag *and* its final pose. Then a skip that fires the event a few frames early still ends with an open gate, because the gate does not depend on the Animation track having played. Quests and objectives: [[Quest Systems]]. ScriptableObject event channels are an alternative to the static event: [[ScriptableObject Architecture]]. ## 4.6 Skip points: a marker that never fires A marker without `INotification` is just data on the timeline. Part 6's controller collects these to offer "skip to next chapter" in long cutscenes, a softer option than skipping the lot. ```csharp // Assets/TimelineAdvanced/Runtime/SkipPointMarker.cs using System; using System.ComponentModel; using UnityEngine.Timeline; namespace TimelineAdvanced { // Pure data: no INotification, so it never fires. The CutsceneController reads these // to "skip to the next chapter" instead of skipping the whole cutscene. [Serializable] [DisplayName("Timeline Advanced/Skip Point")] public class SkipPointMarker : Marker { public string chapterName = "Chapter"; } } ``` Put them on the Markers row at shot or scene boundaries, where a jump looks deliberate. ## 4.7 Use it 1. On the door or gate cutscene from [[Timeline Basics]], add a `GameplayEventReceiver` to the PlayableDirector GameObject. In its `onEvent`, call your gate component (or `Debug.Log` for now). 2. On the Markers row, add a **Gameplay Event** at the moment the gate opens: `eventId = gate.open`, `changesGameState = true`. 3. Add another at the slam: `eventId = camera.shake`, `changesGameState = false`, Retroactive off. 4. Add a **Skip Point** halfway through. 5. Play and let it finish: both events fire. Part 6 shows the skip behaviour. ## 4.8 Exercise Write `MarkerLog : MonoBehaviour, INotificationReceiver` that logs every notification with `origin.GetTime()` and the director's `time`. Put it on the director and scrub, play, pause, jump forward (`director.time += 3` in a debug key) and jump backward. Check each row of the table in 4.2 for yourself. ## Sources - Timeline 1.8 Signals workflow: https://docs.unity3d.com/Packages/[email protected]/manual/wf-signals.html - Timeline 1.8 custom marker workflow (Notes marker, marker editor, USS): https://docs.unity3d.com/Packages/[email protected]/manual/wf-custom-marker.html - `INotificationOptionProvider` (Timeline 1.8): https://docs.unity3d.com/Packages/[email protected]/api/UnityEngine.Timeline.INotificationOptionProvider.html - `SignalReceiver` (Timeline 1.8): https://docs.unity3d.com/Packages/[email protected]/api/UnityEngine.Timeline.SignalReceiver.html - `INotificationReceiver` (6000.5): https://docs.unity3d.com/6000.5/Documentation/ScriptReference/Playables.INotificationReceiver.html - Package source: `Runtime/Playables/TimeNotificationBehaviour.cs`, `Runtime/TimelinePlayable.cs`, `Runtime/Utilities/NotificationUtilities.cs` and `Runtime/Events/Signals/SignalReceiver.cs` in the Timeline 1.8.13 package (Unity package registry). - Observer chapter: https://gameprogrammingpatterns.com/observer.html