Table of Contents

Quests

IRuntimeQuestFactory creates quests that the journal lists, without an .esp file. A quest is declared from stages, objectives, and aliases, and its progress is stored in the co-save and applied again after every load.

This plugin starts a quest to bring an actor a sweetroll:

using SkyrimForge.Events;
using SkyrimForge.Game;
using SkyrimForge.Papyrus;
using SkyrimForge.Quests;
using SkyrimForge.World;
using System;

namespace SkyrimForge.ExamplePlugins;

/// <summary>Starts a quest on Shift+F1 to bring the actor under the crosshair a sweetroll, with a journal objective, a trigger zone, and a calendar timer.</summary>
public sealed class QuestPlugin(GameTarget gameTarget, IGameEvents events, IRuntimeQuestFactory questFactory, ITriggerZoneFactory zoneFactory, ICalendarTimerFactory timerFactory,
    IUtility utility, IDebug debug, ILog log) : IPlugin
{
    /// <inheritdoc/>
    public void Start()
    {
        ICalendarTimer cravingTimer = timerFactory.Create("craving");
        cravingTimer.OnElapsed.Subscribe(_ => debug.Notification("Your friend would like another sweetroll."));
        var friend = new QuestReferenceAlias("Friend");
        var wantedStage = new QuestStage(10, $"{friend} would pay good coin for a sweetroll.")
        {
            ObjectivesToDisplay = [new QuestObjective($"Bring {friend} a sweetroll") { Targets = [friend] }]
        };
        var deliveredStage = new QuestStage(20, $"I brought {friend} a sweetroll, and was paid for it.")
        {
            QuestOutcome = QuestOutcome.Completed,
            SetCallback = async context =>
            {
                const int reward = 100;
                cravingTimer.Start(TimeSpan.FromDays(1));
                PlayerCharacter player = gameTarget.Player;
                await player.Papyrus.RemoveItem(ExampleForms.FoodSweetroll);
                // An await can resume after another save loads. The token is canceled when that load starts.
                context.NewGameOrSaveLoading.ThrowIfCancellationRequested();
                await player.Papyrus.AddItem(KnownForms.Gold001, reward);
            }
        };
        IRuntimeQuest quest = questFactory.Create("sweetroll", "A Sweet Tooth", [wantedStage, deliveredStage], activeOnStart: true);
        zoneFactory.Create("friend", () => friend.ReferenceId, 400f).OnEnter.Subscribe(_ =>
        {
            if (wantedStage.IsCurrent)
            {
                debug.Notification("You still owe your friend a sweetroll.");
            }
        });
        friend.Events.OnPlayerActivate.Subscribe(async _ =>
        {
            await utility.WaitForGameThreadAsync();
            if (!wantedStage.IsCurrent)
            {
                return;
            }
            // Math.Abs matches Papyrus's GetItemCount, which returns the magnitude.
            int sweetrollCount = Math.Abs(gameTarget.Player.GetItemCount(ExampleForms.FoodSweetroll.Form));
            if (sweetrollCount > 0)
            {
                await deliveredStage.SetAsync();
            }
            else
            {
                debug.Notification("You have no sweetroll to give.");
            }
        });
        events.OnKeyDown(BSKeyboardDevice.Keys.Key.kF1, ModifierKeys.Shift).Subscribe(async _ =>
        {
            await utility.WaitForGameThreadAsync();
            if (gameTarget.CrosshairReference?.AsActor() is { } actor)
            {
                quest.RemoveFromJournalAndReset();
                friend.Fill(actor);
                await wantedStage.SetAsync();
            }
        });
        log.Write("Shift+F1 starts the example quest with the actor under the crosshair.");
    }
}
  • The key passed to Create identifies the quest's stored progress. Creating a second quest with the same key throws, and a key changed between versions of the plugin does not find the progress stored under the old one.
  • When SetAsync() sets a QuestStage, the journal shows the stage's log entry and objectives, the quest takes the stage's outcome, and the stage's SetCallback function runs. SetCallback does not run again when a save is loaded.
  • A quest declared in an .esp file is advanced through Papyrus: await quest.Papyrus.SetStage(10) runs the stage's fragment and adds its log entry. Writing the quest's CurrentStage changes the field only.
  • An alias, such as a QuestReferenceAlias, is filled at runtime. Written into an objective's text or a stage's log entry, it is replaced with the name of the reference or location that fills it.
  • Call quest members on the game's thread. A key press or an activation can arrive on a worker thread, so its handler awaits WaitForGameThreadAsync first.
  • ITriggerZoneFactory creates zones around references that raise events as the player enters and leaves them, and ICalendarTimerFactory creates timers on the game's calendar that are saved with the game.