Programmatically Creating a Timeline

Most of the time, timeline creation in Unity is a fairly manual affair. For Arms Race and for the upcoming Desert Angels, this is mostly true for their cutscenes. The scenes take place over a whole Timeline, with entries for animations, sounds, and dialogue.

It’s the ‘dialogue’ bit that I decided to automate for Arms Race, where I had a script and wanted to generate a timeline from scratch with the dialogue already placed, to be edited later.

This can be accomplished by generating TimelineAssets, TrackAssets, and finally TimelineClips via TimelineAsset‘s create API.

var tracks = timelineToUpdate.GetRootTracks();
    DialogueTrack targetTrack = null;

    foreach (TrackAsset track in tracks) {
        Debug.Log("Currently printing track " + track.name);
        Debug.Log(track.GetType());

        if (track.name == "Dialogue") {
            Debug.Log("Removing existing dialogue track");
            foreach (TimelineClip clip in track.GetClips()) {
                timelineToUpdate.DeleteClip(clip);
            }
            targetTrack = (DialogueTrack)track;
        }
    }

    if (!targetTrack) {
        targetTrack = timelineToUpdate.CreateTrack<DialogueTrack>(null, "Dialogue");
}
...
    
// this section of code creates a new clip on the timeline track
// given some base parameters.
TimelineClip clip = targetTrack.CreateClip<DialogueClip>();
DialogueClip dialogueClip = (DialogueClip)clip.asset;

clip.start = timestamp;
clip.duration = action == "hide" ? 1f : 5f;

// these are public variables on the Behavior attached to the Clip.
dialogueClip.template.character = character;
dialogueClip.template.shouldHideDialogueBox = action == "hide" ? true : false;
dialogueClip.template.dialogueText = dialogueText;
dialogueClip.template.x = x;
dialogueClip.template.y = y;

Note that when you programmatically create a timeline like this, the timeline UI in the editor won’t update until you toggle between different timelines! Be sure to refresh it to avoid looking at invalid clips.

References

TimelineClip API

Various Unity forum links: Create timeline assets through script Deleting timeline clips at runtime

Getting a specific type of a clip from a TimelineClip