Unreferenced AnimatorOverrideController objects

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:

AnimationClip clip = Resources.Load("Bodyparts/" + newClipName) as AnimationClip;
Animator anim = transform.Find("body").GetComponent<Animator>();
AnimatorOverrideController overrideController = new AnimatorOverrideController(anim.runtimeAnimatorController);
overrideController[oldClipName] = clip;
anim.runtimeAnimatorController = overrideController;

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!

alt text

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:

    private void OnDestroy()
    {
        Animator anim = transform.Find("body").GetComponent<Animator>();
        if (anim.runtimeAnimatorController.GetType() == typeof(AnimatorOverrideController)) {
            Destroy(anim.runtimeAnimatorController);
        }
    }