Unity使用动画状态机行为(StateMachineBehaviours)

文章介绍了在Unity项目开发中,如何利用StateMachineBehaviours类来监听和管理按钮动画的事件。通过创建一个名为ButtonPressedBehaviour的脚本,重写OnStateEnter和OnStateExit方法,可以在动画状态改变时执行相应的操作。文章提出使用静态字典存储不同按钮的事件委托,以便在动画退出时调用相应的方法,实现了动态绑定和执行事件的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

引言:在项目开发中,当我们为按钮制作自定义动画时,会希望在按钮播放完动画之后再执行事件。

一般会使用延迟执行的方法,但是如果使用StateMachineBehaviours就无需在动画内添加事件帧。

继承StateMachineBehaviours类,将它挂载到动画上,就能监听动画播放的事件。如下:
在这里插入图片描述

脚本部分:


public class ButtonPressedBehaviour : StateMachineBehaviour
{
 
		//动画进入时
    // OnStateEnter is called when a transition starts and the state machine starts to evaluate this state
    override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    {
     
    }
    
    //动画退出时
    // OnStateExit is called when a transition ends and the state machine finishes evaluating this state
    override public void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    {
      
    }
}

这下我们能监听到按钮动画播放状态了 ,但是如何执行我们想要执行的方法呢?为每一个按钮动画都添加不同的类吗?这是不可能的,所以我们可以使用字典类型Dictionary。如下:


public class ButtonPressedBehaviour : StateMachineBehaviour
{
//保存字符串对应的Action委托
    public static Dictionary<string, Action> buttonFunctions = new Dictionary<string, Action>();

    private void Awake()
    {
        buttonFunctions = new Dictionary<string, Action>();
    }
	//动画进入时
    // OnStateEnter is called when a transition starts and the state machine starts to evaluate this state
    override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    {
      
    }
      //动画退出时
    // OnStateExit is called when a transition ends and the state machine finishes evaluating this state
    override public void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    {
    //根据按钮名称执行对应的Action委托(先对buttonFunctions进行添加)
        buttonFunctions[animator.gameObject.name].Invoke();
    }
}

在另一个脚本中进行添加事件监听就好了

ButtonPressedBehaviour.buttonFunctions.add(名称,方法);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值