Search Unity

  1. Unity Asset Manager is now available in public beta. Try it out now and join the conversation here in the forums.
    Dismiss Notice
  2. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  3. Unity support for visionOS is now available. Learn more in our blog post.
    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

    gapMindful

    Joined:
    Jun 26, 2013
    Posts:
    17
    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.         }
    6.  
    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.