unity 动画控制

播放控制

Animator animator;

animator.speed=0;//停止播放
animator.speed=-1;//倒放

animator.Play("stateName",0,0);//播放指定状态(stateName是Animator窗口里各个状态的名称)

跳到指定帧,并停止

Animator animator;

animator.speed=0;//停止播放

AnimationClip clip=animator.runtimeAnimatorController.animationClips[0];
float frameTime=(1f/clip.frameRate)*5;//跳到第5帧

animator.Play("stateName",0,frameTime);//播放指定状态(stateName是Animator窗口里各个状态的名称)

在动画指定的时间里,添加事件函数
注意:函数所在的脚本和Animator 组件必须绑定到同一个GameObject

using UnityEngine;
using System.Collections;

public class TestAnimationEvent:MonoBehaviour{
    
    private void Awake(){
        Animator animator=GetComponent<Animator>();//Animator组件和此脚本必须绑定到同一个GameObject
                
        AnimatorOverrideController overrideController=new AnimatorOverrideController(animator.runtimeAnimatorController);
        //通过子符串获取AnimationClip,注意并不是Animator窗口里各个状态的名称,而是在Animator窗口中选择的状态在Inspector面板的motion属性显示的名称
        AnimationClip clip=overrideController["CINEMA_4D___"];

        //在动画指定的时间,添加事件
        AnimationEvent onCompleteEvent=new AnimationEvent();
        onCompleteEvent.objectReferenceParameter=this;
        onCompleteEvent.functionName=nameof(OnAnimationClipComplete);
        onCompleteEvent.time=clip.length;//clip.length动画长度,单位为秒。这里表示在结束时添加事件
        clip.AddEvent(onCompleteEvent);
    }

    private void OnAnimationClipComplete(UnityEngine.Object objectReference){//注意:参数类型是UnityEngine.Object不是object
        //注意:当内存中拥有多个当前类的实例时,将会调用多次此函数,使用objectReferenceParameter属性传递this区分
        if(objectReference!=this)return;

        Debug.Log("onShakeAnimComplete;");
    }
}

第二种方法:
通过AnimatorStateInfo.normalizedTime判断播放完成

using UnityEngine;
using System.Collections;

public class Test:MonoBehaviour{

    public Animator animator;

    private void Awake(){
        animator.Play("attack");
        InvokeRepeating(nameof(checkStateComplete),0.02f,0.02f);
    }

    private void checkStateComplete(){
        AnimatorStateInfo stateInfo=animator.GetCurrentAnimatorStateInfo(0);
        if(stateInfo.IsName("attack")){
            //normalizedTime:表示动画的标准化时间,区间:[0,1]
            if(stateInfo.normalizedTime>=1.0f) {
                onStateComplete();
                CancelInvoke(nameof(checkStateComplete));
            }
        }
    }
    
    private void onStateComplete(){
        Debug.Log("onStateComplete");
    }
    
    private void OnDestroy(){
        CancelInvoke("checkStateComplete");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值