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 @ 2022-02-22 10:56  小紫苏  阅读(469)  评论(0编辑  收藏  举报