Page 1 of 1

[HOWTO] How To: Respond To Quest State Changes in Script

Posted: Thu Aug 05, 2021 2:20 pm
by Tony Li
To set up your own scripts to be notified when quest states change, listen for the Message System message "Quest State Changed", like in this script:

Code: Select all

using UnityEngine;
using PixelCrushers;
using PixelCrushers.QuestMachine;

public class LogQuestStateChanges : MonoBehaviour, IMessageHandler
{
    private void OnEnable()
    {
        // Listen for Quest State Changed messages:
        MessageSystem.AddListener(this, QuestMachineMessages.QuestStateChangedMessage, string.Empty);
    }

    private void OnDisable()
    {
        // Stop listening:
        MessageSystem.RemoveListener(this);
    }

    public void OnMessage(MessageArgs messageArgs)
    {
        // We received a quest state changed message. Log the state.
        // Parameter: Quest ID. 
        // Argument 0: [StringField] Quest node ID, or null for main quest state.
        // Argument 1: [QuestState] / [QuestNodeState] New state.
        // (See: https://pixelcrushers.com/quest_machine/api/html/class_pixel_crushers_1_1_quest_machine_1_1_quest_machine_messages.html#aa4a3f28c8cdce110a1204d1a361e537a)
        string questID = messageArgs.parameter;
        if (messageArgs.values[0] == null) // (null means this message is for main quest state)
        {
            QuestState state = (QuestState)messageArgs.values[1];
            Debug.Log($"Quest '{questID}' changed to state {state}");
        }
        else
        {
            StringField nodeID = (StringField)messageArgs.values[0];
            QuestNodeState state = (QuestNodeState)messageArgs.values[1];
            Debug.Log($"Quest '{questID}' node '{nodeID}' changed to state {state}");
        }
    }
}