Inspiaaa / UnityHFSM

A simple yet powerful class-based hierarchical finite state machine for Unity
MIT License
1.05k stars 121 forks source link

Call OnEnter after updating transitions and triggers #7

Closed shiena closed 3 years ago

shiena commented 3 years ago

Trigger does not work within OnEnter. This is because OnEnter is called before activeTransitions and activeTriggerTransitions are updated, so the transition list and state do not match. Therefore, OnEnter should be called after activeTransitions and activeTriggerTransitions are updated.

using FSM;
using UnityEngine;

public class Foo : MonoBehaviour
{
    private StateMachine stateMachine;

    private void Awake()
    {
        stateMachine = new StateMachine(this);

        stateMachine.AddState("Run", new State());
        stateMachine.AddState("Jump", new State(onEnter: s =>
        {
            Debug.Log(stateMachine.ActiveStateName);
            stateMachine.Trigger("ToGround");
            Debug.Log(stateMachine.ActiveStateName); // expect "Ground" but it's "Run"
        }));
        stateMachine.AddState("Ground", new State());

        stateMachine.AddTriggerTransition("ToJump", new Transition("Run", "Jump"));
        stateMachine.AddTriggerTransition("ToGround", new Transition("Jump", "Ground")); // expect transition
        stateMachine.AddTriggerTransition("ToGround", new Transition("Run", "Run")); // actual transition

        stateMachine.SetStartState("Run");

        stateMachine.Init();
        stateMachine.Trigger("ToJump");
    }
}

Output before modification

Jump
Run

Output after modification

Jump
Ground
Inspiaaa commented 3 years ago

Thanks for the suggested reordering! I see it makes sense and works. I will merge this pull request. 👍