Unity——动画Animator的方法调用

关于动画的播放、获取该对象的所有动画名、当前名及时间长度

    private Animator animator;
    private AnimationClip[] animationClip;
    void Start()
    {
        animator = GetComponent<Animator>();
        animationClip = animator.runtimeAnimatorController.animationClips;
        Debug.Log("该对象有" + animationClip.Length + "个动画");
        foreach(AnimationClip a in animationClip)//遍历获取所有该对象的动画名
        {
            Debug.Log(a.name);
        }
    }
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.A))
        {
            Debug.Log("按下A");
            animator.Play(animationClip[0].name);   //播放动画
            animator.Update(0);         //刷新0层的动画,默认新建的动画在0层。
            GetAnimatorInfo();
        }
        if (Input.GetKeyDown(KeyCode.B))
        {
            Debug.Log("按下B");
            animator.Play(animationClip[1].name);
            animator.Update(0);
            GetAnimatorInfo();
        }
    }
    void GetAnimatorInfo()
    {
        string name = animator.GetCurrentAnimatorClipInfo(0)[0].clip.name;//获取当前播放动画的名称
        Debug.Log("当前播放的动画名为:" + name);
        float length = animator.GetCurrentAnimatorClipInfo(0)[0].clip.length;//获取当前动画的时间长度
        Debug.Log("播放动画的长度:" + length);
    }

输出显示:

播放与暂停

播放有两种方式

animator.speed = 1;//动画播放速度为1,即播放

或    animator.enabled = true;//播放

暂停同样的

animator.speed = 0;//动画播放速度为0,即暂停

或    animator.enabled = false;//暂停

动画的播放

animator.Play("name", 0, 0.5f);//括号中分别表示:要播放的动画名称,动画所在的层,希望从哪个时间段开始播放。

animator.Play("name"); 一样的,只是所在层及播放位置默认为0。

发布了28 篇原创文章 · 获赞 14 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/Ro969668074/article/details/104673725