Hi, I have Animator controller object and for some states I added my behavoiur class which derives from StateMachineBehaviour. This class has member variable holding callback and notifies me on animation state exit.
Unfortunately, I found, that every time I call SetActive(false) on GameObject which has Animator component and then again SetActive(true), my behaviour class is newly instanced. So, I am loosing any previous setup of callback as I have new class.
Is creating new instance of behaviour class every time on SetActive(true) intended behaviour? It looks, like it is wasting of memory and adds complexity into game code (need for repeated setups).
Thanks. If: “The reason why you lose everything on enable/disable is because normally in unity when an object is disable it does free all the resources used by the gameobject: memory, asset, handle, etc…”, then I think it is not good solution at least for StateMachineBehaviour (SMB). You are adding it to Animator to enhance its behaviour and unless you want to destroy it, you would probably like it to stay there with settings you did from code, as settings from Editor is not possible (as it is not MonoBehaviour).
I thought that, setting something inactive removes it from scene tree processing unless you activate it back again (it is just skipped). But if there is allocation/deallocation every time it can be pretty expensive. I would expect this to happen when I want destroy whole GameObject or particular Component, but not when temporarily disabling it.
Agreed. It’s not perfect, but we have to live with what we have. You could put your persistent data on a MonoBehaviour component. In your StateMachineBehaviour’s OnStateEnter, just find the MonoBehaviour:
public class MyData : MonoBehaviour {
...
}
public class MySMB : StateMachineBehaviour {
private MyData myData;
public override void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) {
myData = animator.GetComponent<MyData>();
}
}