Search Unity

Many unreferenced AnimatorOverrideController objects

Discussion in 'Animation' started by Jinxology, Jul 8, 2018.

  1. Jinxology

    Jinxology

    Joined:
    Jul 13, 2013
    Posts:
    95
    I've been hunting a memory leak in my game, and I've found a potential culprit! In the profiler, I've noticed a number of unreferenced AnimatorOverrideController objects, and the number keeps growing. The offending code is:

    Code (CSharp):
    1.  
    2. AnimationClip clip = Resources.Load("Bodyparts/" + newClipName) as AnimationClip;
    3. Animator anim = transform.Find("body").GetComponent<Animator>();
    4. AnimatorOverrideController overrideController = new AnimatorOverrideController(anim.runtimeAnimatorController);
    5. overrideController[oldClipName] = clip;
    6. anim.runtimeAnimatorController = overrideController;
    7.  
    As you can see from the profiler screenshot below, the ref count on several is blank (zero?). I'm guessing that the original anim.runtimeAnimatorController is getting lost and left behind. However, when I tried to Destroy() the original controller, it told me "Destroying assets is not permitted to avoid data loss.". How can I prevent these unreferenced objects? Halp!

     
  2. Jinxology

    Jinxology

    Joined:
    Jul 13, 2013
    Posts:
    95
    Figured it out. For some reason, when you Destroy() the object that you've set runtimeAnimatorController on, it doesn't destroy the new override controller you replaced it with. You need to manually destroy that. I used the code:

    Code (CSharp):
    1.      private void OnDestroy()
    2.      {
    3.          Animator anim = transform.Find("body").GetComponent<Animator>();
    4.          if (anim.runtimeAnimatorController.GetType() == typeof(AnimatorOverrideController)) {
    5.              Destroy(anim.runtimeAnimatorController);
    6.          }
    7.      }
    Hope that helps someone else having this issue.