留个档,Unity Animator state节点的Motion动态替换AnimationClip

前言

·由于Unity没有提供直接替换的API,所以在仅限的API下进行逻辑操作。

·替换的原理是差不多的,利用AnimatorOverrideController,进行运行时的覆盖。

·网上搜索很多文章是利用 名字字符串作为hash的key来进行替换。不满足我自己项目中的需求,于是利用GetOverrides 和 ApplyOverrides,封装了这个功能。

思考过程

·因为Animator的操作是UnityeEditor级别的,所以需要AnimatorOverrideController来辅助操作。

· AnimatorOverrideController的两个接口的特性会针对一个数据结构List<KeyValuePair<AnimationClip, AnimationClip>>。 查API就可以知道, 是from to的概念。
我自己做了测试,理解上可以认为, KeyValuePair里的key指的是原本Animator中的动画文件。 value是需要替换的AnimationClip。

·因为需要进行替换,节点里的动画不能为空。不然就没法拿来替换了。

·我要实现的模块,可以提供接口,是针对state节点的名字,进行操作的,需要一个映射关系。


所以,这个模块的设计,那么就会是Animator一开始会有一套默认的AnimationClip存在于各个state中。这一步我认为是静态过程即可。
我还需要一个state名字和默认clip之间的对应关系, 这个静态即可, 这在UnityEditor下很容易处理。并且序列化就行了。
之后就是写逻辑了


/*
 * Create by fox.huang 黄文叶
 * time: 2023.6.24
 * 
 * UnityAPI提供的替换逻辑,只能通过指定Clip的名字,或者指定Clip对象进行替换
 * 针对State的修改,是在UnityEditor下的,也就是runTime不能用。所以这个类的目的是实现State映射clip的修改。
 *
 * 注意:为了区分唯一性,同layer内,不能出现重名的节点(在使用子状态机的时候,会出现同名情况)
 */
using System.Collections.Generic;
using UnityEngine;

#if UNITY_EDITOR
using UnityEditor.Animations;
using UnityEditor;
using System.IO;
#endif

/// <summary>
/// Animator节点上的AnimationClip替换组件。
/// </summary>
public class AnimatorClipReplaceComponent : MonoBehaviour
{
    [System.Serializable]
    public class Pack
    {
        //这边的序列化应该灰显的 懒得写了,就这么用呗。
        [SerializeField] public string m_strName = null;        // 节点的名字
        [SerializeField] public int m_nLayer = 0;
        [SerializeField] public AnimationClip m_aniClipDefault = null; //默认的动画clip

        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="strName">节点名字</param>
        /// <param name="aniClipDefault">默认动画名字</param>
        public Pack(string strName, int nLayer, AnimationClip aniClipDefault)
        {
            m_strName = strName;
            m_nLayer = nLayer;
            m_aniClipDefault = aniClipDefault;
        }
    }

#if UNITY_EDITOR
    [Tooltip("创建填充用AnimationClip的路径(空节点也认为是有效节点,创建默认clip用作替换依据)")]
    [SerializeField] string m_strClipAssetCreatePath = "Assets/Art/Animation";
    /// <summary>
    /// 刷新当前的列表
    /// </summary>
    [ContextMenu("Refresh Default State Node List")]
    private void RefreshList()
    {
        Animator ani = this.GetComponent<Animator>();
        if (ani == null)
        {
            Debug.LogError("AnimatorClipReplaceHelper RefreshList, can not find component Animator in "
                + this.gameObject.name);
            return;
        }
        
        string strAssetPath = AssetDatabase.GetAssetPath(ani.runtimeAnimatorController);
        AnimatorController animatorController = AssetDatabase.LoadAssetAtPath<AnimatorController>(strAssetPath);
        if (animatorController == null)
        {
            Debug.LogError("AnimatorClipReplaceHelper RefreshList, can not load asset : "
                + strAssetPath);
            return;
        }

        //创建默认clip的文件夹
        CreateFolder(m_strClipAssetCreatePath);

        //开始遍历AnimatorCrontroller
        var layers = animatorController.layers;
        int nLayerCount = layers.Length;
        m_listInfos = new List<Pack>();
        for (int i = 0; i < nLayerCount; i++)
        {
            var oneLayer = layers[i];
            CollectStates(oneLayer.stateMachine.states, i);
            CollectStateMachines(oneLayer.stateMachine.stateMachines, i);
        }

        //重新保存一次AnimatorController
        EditorUtility.SetDirty(animatorController);
        AssetDatabase.SaveAssets();
    }

    private void CreateFolder(string strPath)
    {
        string strFullPath = strPath.Replace("Assets", Application.dataPath);
        if (!Directory.Exists(strFullPath))
        {
            Directory.CreateDirectory(strFullPath);
        }
    }

    /// <summary>
    /// 递归收集节点们的信息
    /// </summary>
    private void CollectStates(ChildAnimatorState[] states, int nLayer)
    {
        int nCount = states.Length;
        for (int i = 0; i < nCount; i++)
        {
            var oneState = states[i].state;
            string strName = oneState.name;

            if (oneState.motion == null)
            {
                AnimationClip newClip = new AnimationClip();
                string strLocalPath = m_strClipAssetCreatePath + "aniclip_def_" +
                    strName.ToLower() + "_" + i.ToString() +
                    ".anim";
                AssetDatabase.CreateAsset(newClip, strLocalPath);
                AssetDatabase.ImportAsset(strLocalPath);
                oneState.motion = AssetDatabase.LoadAssetAtPath<AnimationClip>(strLocalPath);
            }

            m_listInfos.Add(new Pack(strName, nLayer, (AnimationClip)oneState.motion));
        }
    }

    /// <summary>
    /// 递归收集子状态机的内容
    /// </summary>
    private void CollectStateMachines(ChildAnimatorStateMachine[] group, int nLayer)
    {
        if (group == null)  // 安全判断
        {
            return;
        }
        int nCount = group.Length;
        if (nCount == 0)    // 安全判断
        {
            return;
        }
        for (int i = 0; i < nCount; i++)
        {
            var one = group[i].stateMachine;
            CollectStates(one.states, nLayer);
            CollectStateMachines(one.stateMachines, nLayer);
        }
    }

#endif


    /// <summary>
    /// Animator节点名字对应的信息集合
    /// </summary>
    [SerializeField] List<Pack> m_listInfos = null;
    private Dictionary<string, AnimationClip> m_dicDefaultClips = null;

    [SerializeField] Animator m_animator = null;
    private List<KeyValuePair<AnimationClip, AnimationClip>> m_listRuntime
        = new List<KeyValuePair<AnimationClip, AnimationClip>>();
    private AnimatorOverrideController m_aoc = null;

    private void Awake()
    {
        //创建一个AnimatorOverrideController作为替换的容器
        if (m_animator == null)
        {
            m_animator = this.GetComponent<Animator>();
        }
        if (m_animator == null)
        {
            Debug.LogError("AnimatorClipReplaceHelper Awake, no Animator : " + this.gameObject.name);
            return;
        }
        m_aoc = new AnimatorOverrideController(m_animator.runtimeAnimatorController);
        m_aoc.name = "aoc_" + this.gameObject.name;
        m_animator.runtimeAnimatorController = m_aoc;

        //获取到当前clip的列表
        m_aoc.GetOverrides(m_listRuntime);

        m_dicDefaultClips = new Dictionary<string, AnimationClip>();
        //序列化信息 转换成 键值对
        int nCount = m_listInfos.Count;
        for (int i = 0; i < nCount; i++)
        {
            var pack = m_listInfos[i];
            string strKeyName = pack.m_strName + pack.m_nLayer.ToString();
            if (m_dicDefaultClips.ContainsKey(strKeyName))
            {
                Debug.LogWarning("AnimatorClipReplaceHelper Awake, already has node : " + pack.m_strName);
                continue;
            }
            m_dicDefaultClips.Add(strKeyName, pack.m_aniClipDefault);
        }
    }

    /// <summary>
    /// 对一个节点的AnimationCLip进行替换
    /// </summary>
    /// <param name="strStateName">节点名</param>
    /// <param name="aniClip">动画Clip(为null的时候还原到默认)</param>
    public void MarkReplace(string strStateName, AnimationClip aniClip, int nLayer = 0)
    {
        strStateName += nLayer.ToString();
        AnimationClip aniClipDefault;
        if (!m_dicDefaultClips.TryGetValue(strStateName, out aniClipDefault))
        {
            Debug.LogWarning("AnimatorClipReplaceHelper MarkReplace, no state be find " +
                strStateName + " in layer: " + nLayer);
            return;
        }

        if (aniClip == null)
        {
            aniClip = aniClipDefault;
        }

        int nCount = m_listRuntime.Count;
        for (int i = 0; i < nCount; i++)
        {
            if (m_listRuntime[i].Key == aniClipDefault)
            {
                m_listRuntime[i] = new KeyValuePair<AnimationClip, AnimationClip>(aniClipDefault, aniClip);
                break;  // 这里break,因为获取到的kv list是去重的
            }
        }
    }

    /// <summary>
    /// 把之前记录的修改,刷新到控件上
    /// </summary>
    public void Flush()
    {
        m_aoc.ApplyOverrides(m_listRuntime);
    }

}


使用

在用的时候在这里插入图片描述
· 我会先通过UnityEditor ContextMenu按钮的方式把 映射关系和默认clip保存写到序列化。那么这个prefab就可以作为一个单独的对象加载了。 他可以是一个骨骼的prefab也可以是其他。

·Runtime时,MarkReplace进行state名字对应的AnimationClip的设定,最后Flush,进行批量应用刷新。


程序学无止尽。
欢迎大家沟通,有啥不明确的,或者不对的,也可以和我私聊
我的QQ 334524067 神一般的狄狄

猜你喜欢

转载自blog.csdn.net/qq_37776196/article/details/131300166