Unity中Animator动态添加AnimationClip

AnimatorController中一下加载大量动画,会使游戏内存增大很多,所以想动态增加AnimatorController中的动画,达到使用那个动画就加载对应动画的功能。
研究后发现可以通过AnimatorOverrideController实现。通过替换动画的方式,用需要播放的动画将控制器中指定的一个动画替换,这样能间接达到动态加载的功能

using UnityEngine;
public class test : MonoBehaviour
{
    public Animator m_Animator;
    public RuntimeAnimatorController m_RuntimeAnimatorController;
    string mOriginClipName = "play";

    void OnGUI()
    {
        if (GUI.Button(new Rect(0, 0, 50f, 50f), "Pose01"))
            UpDateAnimator("player@pose01");
        else if (GUI.Button(new Rect(60, 0, 50f, 50f), "Pose02"))
            UpDateAnimator("player@pose02");
        else if (GUI.Button(new Rect(120, 0, 50f, 50f), "Pose03"))
            UpDateAnimator("player@pose03");
        else if (GUI.Button(new Rect(180, 0, 50f, 50f), "Pose04"))
            UpDateAnimator("player@pose04");
        else if (GUI.Button(new Rect(0, 60, 50f, 50f), "Stand"))
            m_Animator.Play("standby");
    }

    void UpDateAnimator(string pAnimResourceName)
    {
        var tOverrideController = new AnimatorOverrideController();
        tOverrideController.runtimeAnimatorController = m_RuntimeAnimatorController;

        var mAnimationClips = Resources.LoadAll(pAnimResourceName);
        if (mAnimationClips.Length <= 0)
            return;

        tOverrideController[mOriginClipName] = mAnimationClips[0];
        m_Animator.runtimeAnimatorController = null;
        m_Animator.runtimeAnimatorController = tOverrideController;
        m_Animator.Play(mOriginClipName, 0, 0);
        Resources.UnloadUnusedAssets();
    }
}

其中:

1

2

3

m_Animator.runtimeAnimatorController = null;

 

Resources.UnloadUnusedAssets();

两行很关键,没有这两行,会出现错乱或者内存持续增加

你可能感兴趣的:(Unity3D)