Unity中Animator动态添加AnimationClip
程序员文章站
2022-05-04 19:55:30
...
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("[email protected]");
else if (GUI.Button(new Rect(60, 0, 50f, 50f), "Pose02"))
UpDateAnimator("[email protected]");
else if (GUI.Button(new Rect(120, 0, 50f, 50f), "Pose03"))
UpDateAnimator("[email protected]");
else if (GUI.Button(new Rect(180, 0, 50f, 50f), "Pose04"))
UpDateAnimator("[email protected]");
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<AnimationClip>(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 |
|
两行很关键,没有这两行,会出现错乱或者内存持续增加