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

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

一般会使用延迟执行的方法,但是如果使用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(名称,方法);

猜你喜欢

转载自blog.csdn.net/qq_41727685/article/details/129889937