Search Unity

Question Keep StateMachineBehaviour instance without keepAnimatorControllerStateOnDisable?

Discussion in 'Animation' started by R1PFake, Sep 13, 2021.

  1. R1PFake

    R1PFake

    Joined:
    Aug 7, 2015
    Posts:
    540
    By default all StateMachineBehaviours of an Animator will be destroyed/recreated everytime the "parent" GameObject is disabled/enabled.

    Depending on the use case this can be annoying because:

    1, You have to run your "setup" logic again, for example if your have a MonoBehavior which sets a property on the StateMachineBehaviours instance, you will have to run this code everytime the GameObject is enabled, because the previous StateMachineBehaviours is no longer used and a new one was created

    2, It allocates new instances, so new garbage for the GC, which you want to avoid in same use cases

    The Animator keepAnimatorControllerStateOnDisable does not mention this in the manual, but setting this property to true will also disable this behavior, so the StateMachineBehaviours of the Animator will no longer be destroyed and recreated, so this can be used in some cases, but it will also keep the other Animator states.

    So finally my question: Is there any way to achieve both, reset the animator state but keep the same StateMachineBehaviour instances during disable?

    In an older post they explained they destroy the whole instance everytime because they want to release the memory, which does not make sense to me, because with that logic they would also have to destory every single MonoBehavior when you disable the GameObject, which would be even more annoying.
     
  2. kaarloew

    kaarloew

    Joined:
    Nov 1, 2018
    Posts:
    360
    The keepAnimatorControllerStateOnDisable seems to be a hack.

    I don't understand why there can't be multiple options for this.
    1. Stop playback and reset on disable
    2. Stop playback, but keep the state on disable
    3. Continue playback on disable

    Specially the option 2 is missing