Unity—动画事件传递

动画机在子节点的预制体上,动画事件函数需要在Animator组件同一个GameObject上;

写起来会比较麻烦,用事件将动画事件传递到父物体的脚本中;

public class AnimaEventDelivery : MonoBehaviour
{
    [Header("指定传递动画事件")] public GameObject animaGO;
    [Header("向上传递事件")] public bool isParentDelivery = true;

    //事件
    public void OnAnimaEvent(string args)
    {
        if (isParentDelivery)
        {
            var receive = gameObject.GetComponentsInParent<IAnimaEvent>();
            if (receive != null)
            {
                for (int i = 0; i < receive.Length; i++)
                {
                    receive[i].OnAnimaEvent(args);
                }
            }
        }
        else if (animaGO != null)
        {
            var e = animaGO.GetComponent<IAnimaEvent>();
            if (e == null)
                Debug.LogError("Monohavior not implement IAnimaEvent");
            else
                e.OnAnimaEvent(args);
        }
    }
}

//普通传递事件,接口
public interface IAnimaEvent
{
    void OnAnimaEvent(string args);
}

在父节点中继承IAnimaEvent接口,实现方法;

拦截string参数,响应不同事件;

public class Hero :IAnimaEvent
{
 	//动画事件传递
    public void OnAnimaEvent(string args)
    {
        if (args == "HitEnd")
        {
            Debug.log("HitEnd");
        }
        else if (args == "Fire")
        {
            Debug.log("Fire");
        }
        else if (args == "Die")
        {
            Debug.log("Die");
        }
    }
}

perfab节点挂AnimaEventDelivery脚本;

添加动画事件,设置不同string参数;

posted @   小紫苏  阅读(510)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示