Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We’re making changes to the Unity Runtime Fee pricing policy that we announced on September 12th. Access our latest thread for more information!
    Dismiss Notice
  3. Dismiss Notice

Can't Only Use OnStart to Find StateMachineBehaviours

Discussion in 'Unity 5 Pre-order Beta' started by gapMindful, Oct 29, 2014.

  1. gapMindful


    Jun 26, 2013
    In short: A MonoBehaviour can't know if its attached anaimator's state machine has created new StateMachineBehaviours just by using its OnStart method.

    I started hooking into animation event handling using the new StateMachineBehavriour. But I noticed a bit of an inconsistency from what is explained in this tutorial

    By logging from their constructors, I've seen that the AnimationStateBehaviours attached to the state machine get re-instantiated on each awake call for that gameObject. Unfortunately, that's not just on the initial awake call that invokes my MonoBehaviour's "OnStart" method. This means that, if I cache out all of my references to the animator's custom StateMachineBehaviours on "Start" like is recommend in the tutorial then I'm going to miss all states behaviors created after future awake calls.

    I've been able to work around this by
    • A) Having my monoBehaviour call GetBehaviour on the animator in OnEnable rather than OnStart
    • B) Having my state object find my attached monoBehaviour using a call to the animator's getComponent method in the state's overrriden events.
    Code (CSharp):
    1.         public override void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    2.         {
    3.             CheckInWithControllers(animator);
    4.             eventController.HandleAnimationHookExit(stateInfo);
    5.         }
    7.         private void CheckInWithControllers(Animator animator)
    8.         {
    9.             if (!isCheckedIn)
    10.             {
    11.                 eventController = animator.GetComponent<AnimationEventControllerImpl>();
    12.                 isCheckedIn = true;
    13.             }
    14.         }
    But both seem like a pretty ugly work around and I'd rather just be able to avoid all the subsequent GetComponent / GetBehaviour calls by relying on the OnStart method the tutorial mentions.
    huulong likes this.