Search Unity

  1. We are migrating the Unity Forums to Unity Discussions. On July 12, the Unity Forums will become read-only.

    Please, do not make any changes to your username or email addresses at id.unity.com during this transition time.

    It's still possible to reply to existing private message conversations during the migration, but any new replies you post will be missing after the main migration is complete. We'll do our best to migrate these messages in a follow-up step.

    On July 15, Unity Discussions will become read-only until July 18, when the new design and the migrated forum contents will go live.


    Read our full announcement for more information and let us know if you have any questions.

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.