您的位置:首页 > 移动开发 > Unity3D

Unity—动画事件传递

2022-02-22 10:56 579 查看

动画机在子节点的预制体上,动画事件函数需要在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参数;

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: