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参数;
Life is too short for so much sorrow.
本博客所有文章除特别声明外,均采用
CC BY-NC-SA 4.0 许可协议。转载请注明来自 小紫苏!