[HOWTO] How To: Start Quest From Script
Posted: Mon Oct 19, 2020 10:19 am
This post explains how to give a quest without using a QuestGiver.
The most common way to give a quest to a quester (e.g., player) is to use a QuestGiver component. You can either call QuestGiver.StartDialogueWithPlayer() to show the accept/decline UI, or call QuestGiver.GiveQuestToQuester() (or the equivalent visual scripting action) to give it directly without using UI. Note that you can add a QuestGiver to an empty GameObject. It doesn't have to have a visual representation in the scene.
However, if you don't want to use a QuestGiver, you can give the quest directly to the player and activate it using a few lines of scripting. Here's an example script that gives a quest to a player. It takes care of all of the housekeeping of clearing the player's quest journal of old copies of the quest, activating the quest properly so its listeners also activate, etc.
GiveQuest.cs
Alternatives
The most common way to give a quest to a quester (e.g., player) is to use a QuestGiver component. You can either call QuestGiver.StartDialogueWithPlayer() to show the accept/decline UI, or call QuestGiver.GiveQuestToQuester() (or the equivalent visual scripting action) to give it directly without using UI. Note that you can add a QuestGiver to an empty GameObject. It doesn't have to have a visual representation in the scene.
However, if you don't want to use a QuestGiver, you can give the quest directly to the player and activate it using a few lines of scripting. Here's an example script that gives a quest to a player. It takes care of all of the housekeeping of clearing the player's quest journal of old copies of the quest, activating the quest properly so its listeners also activate, etc.
GiveQuest.cs
Code: Select all
using UnityEngine;
using PixelCrushers;
using PixelCrushers.QuestMachine;
public class GiveQuest : MonoBehaviour
{
public Quest questAsset;
public QuestJournal questJournal;
void Start()
{
// Make a copy of the quest for the quester:
var questInstance = questAsset.Clone();
// Add the copy to the quester and activate it:
var questerTextInfo = new QuestParticipantTextInfo(questJournal.id, questJournal.displayName, questJournal.image, null);
questInstance.AssignQuester(questerTextInfo);
questInstance.timesAccepted = 1;
questJournal.deletedStaticQuests.Remove(StringField.GetStringValue(questInstance.id));
questJournal.AddQuest(questInstance);
questInstance.SetState(QuestState.Active);
QuestMachineMessages.RefreshUIs(questInstance);
}
}
Alternatives
- At design time, you can assign the quest to the player's Quest Journal component > Quests list. In this case, you'll probably want to set the quest state and initial quest nodes' states to Active, or configure Autostart Conditions.
- Or add a Quest Giver component to an empty GameObject. (Quest Giver components don't always have to be on visible NPCs.) Then call methods on it such as QuestGiver.GiveAllQuestsToPlayer().