0
\$\begingroup\$

When I start my game I get null-references in my OnStateExit of objects that are initialized in the OnStateEntered. After this it goes smooth, so it only occurs at startup before any conditions for statechanges are met.

How come? My understanding is that OnStateExit is always preceded by OnStateEntered.

My StateBehaviour

public class DuckStateBehaviour : BaseStateBehaviour {

    override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) 
    {
        base.OnStateEnter(animator, stateInfo, layerIndex);
        mMovement.BeginDuck();
    }

    public override void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    {
        if (mMovement != null) mMovement.EndDuck();
        base.OnStateExit(animator, stateInfo, layerIndex);
    }
}

public class BaseStateBehaviour : StateMachineBehaviour {

    protected Transform mTransform = null;
    protected Rigidbody2D mRigidBody = null;
    protected IMovement mMovement = null;

    public override void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    {
        mTransform = animator.gameObject.GetComponent<Transform>();
        mRigidBody = animator.gameObject.GetComponent<Rigidbody2D>();
        mMovement = animator.gameObject.GetComponent<IMovement>();

        Debug.Assert(mTransform != null);
        Debug.Assert(mRigidBody != null);
        Debug.Assert(mMovement != null);
    }

}
\$\endgroup\$
  • \$\begingroup\$ I'm not sure if it's of any help (I'm not familiar with Unity), but the documentation does not seem to say " that OnStateExit is always preceded by OnStateEntered." It says that OnStateEnter_"- Called on the first Update frame when a statemachine evaluate this state."_ and OnStateExit "- Called on the last update frame when a statemachine evaluate this state." Maybe the 'default' state is unloaded but not explicitly loaded. And maybe it's a bug. \$\endgroup\$ – Vaillancourt Aug 7 '16 at 14:26
  • \$\begingroup\$ That would suggest that their is a last update frame when the statemachine evaluates this state but no first update frame. This smells very weird. \$\endgroup\$ – bbnkttp Aug 7 '16 at 14:58
2
\$\begingroup\$

In case you have a transition, one state can start and the other can still be executing (updating): So yes, they can happen in the "wrong" way.

| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.