Unity中动画与触发事件的分解
发表于2018-05-31
Unity中,模型的行为通常是与动画同时发生的,但是在处理过程中,我们又需要把播放动画与行为触发分开实现,来达到代码的简介与功能的划分,这时候就要用到事件与委托。在这里我们用一个AnimationEventBehaviour工具类将其实现。
类的思想是创建一个事件,之后由策划人员来绑定播放动画到什么时间触发事件。而程序端(用player脚本模拟)只需要控制动画的播放时机以及进行事件触发行为的绑定,这样就很好的达到了划分功能,单一职责的要求。
具体操作由一些图片进行解释
在模型上绑上脚本AnimationEventBehaviour后,如此进行事件的绑定:

组件结构如图

AnimationEventBehaviour脚本与其绑定在player上的测试函数如下:
public class AnimationEventBehaviour : MonoBehaviour
{
/*
程序职责:
在某个脚本播放动画,定义攻击的具体逻辑,绑定到事件。
策划:
将当前脚本附加给模型,在Unity编译器中设置动画片段的事件(攻击,取消动画)
*/
//在脚本中注册事件
public event Action attackHandler;
private Animator anim;
private void Start()
{
anim = GetComponentInChildren<Animator>();
}
//策划在Unity编译器中指向当前方法
public void OnAttack()
{
if (attackHandler != null)
attackHandler();
}
//策划在Unity编译器中指向当前方法
public void OnCancelAnim(string animPara)
{
anim.SetBool(animPara, false);
}
}
private new void Awake()
{
GetComponentInChildren<AnimationEventBehaviour>().attackHandler += OnAttacking;
}
<span style="white-space:pre;"> </span>
//攻击时仅调用次方法,进行动画的播放
public void Attack()
{
//播放攻击动画
GetComponentInChildren<Animator>().SetBool("attack1", true);
}
public void OnAttacking()
{
Debug.Log("攻击");
}
<span style="white-space:pre;"> </span>
来自:https://blog.csdn.net/hacker9403/article/details/78218687
