State observer

Watch the flow from outside it for analytics and debugging.

Each StateFlow Asset has an IStateObserver that announces every move the flow makes. Subscribe to it for analytics, breadcrumbs for crash reports, debug overlays or tutorials that react to where the player is.

The API

IStateObserver.cs
public interface IStateObserver
{
    string FromStateGuid { get; }   // the state the last transition left
    string ToStateGuid { get; }     // the state it entered
    object Payload { get; }         // what it carried, or null

    void Subscribe(Action<Tuple<string, string>> action);
    void Unsubscribe(Action<Tuple<string, string>> action);
}

Get it from a running manager with manager.StateObserver, or from the asset with asset.StateObserver. Subscribers receive the from and to state guids. Payload is already set when they are called, so read it from the observer.

Example: logging every move

ObserverLog.cs
using System;
using System.Linq;
using StateFlow.Runtime.Components.Designer.Impl;
using UnityEngine;

public class ObserverLog : MonoBehaviour
{
    [SerializeField] private StateFlowManager manager;

    private void Start()
    {
        manager.StateObserver.Subscribe(OnStateChanged);
    }

    private void OnDestroy()
    {
        manager.StateObserver.Unsubscribe(OnStateChanged);
    }

    private void OnStateChanged(Tuple<string, string> change)
    {
        if (string.IsNullOrEmpty(change.Item2))
        {
            return;   // the manager is shutting down
        }

        var payload = manager.StateObserver.Payload;
        Debug.Log($"{NameOf(change.Item1)} → {NameOf(change.Item2)} {payload}");
    }

    // StateFlowData includes every machine and linked asset the manager runs.
    private string NameOf(string guid)
    {
        var state = manager.StateFlowData.StateMachines
            .SelectMany(machine => machine.States)
            .FirstOrDefault(candidate => candidate.Guid == guid);

        return state != null ? state.Name : "start";
    }
}
Play mode
A log panel listing observer notifications such as 'Observer Alpha → Beta (Hello from Alpha)' between lifecycle calls.
Observer lines in the 05 sample's log. A notification arrives before the states' Exit and Initialize calls for that move.

Good to know

Try it

Import Feature Samples from the Package Manager and open 05 Lifecycle and Observer/05 Lifecycle and Observer.unity. About the samples