Unity动画执行代码封装 循环执行 与 执行一次后运行其他逻辑等

公司的项目里 需要大量的动画 因此专门封装了一个关于动画的类 只要挂载在存在Animator动画组件的物体上 就可以直接调用函数 初学自用 分享思路 以后技术上来了 会继续更新修改

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class AniObj : MonoBehaviour
{
    private Animator _animator;
    private string _aniName;
    private Action _onTrigger;
    public bool IsPlay;
    // Start is called before the first frame update
    void Start()
    {
        
    }
    private void OnEnable()
    {
        Init();

    }
    // Update is called once per frame
    void Update()
    {
        if (IsPlay)
        {
            AnimatorStateInfo animatorInfo;
            animatorInfo = _animator.GetCurrentAnimatorStateInfo(0);
            string animString = _animator.GetCurrentAnimatorClipInfo(0)[0].clip.name;

            if ((animatorInfo.normalizedTime > (1f-Time.deltaTime)) && (animString == _aniName))
            {
                _onTrigger();
                IsPlay = false;
            }

        }
    }
    void Init()
    {
        _animator = GetComponent();
    }
    /// 
    /// 运行一次动画
    /// 
    /// 
    /// 
    /// 
    /// 
    public void PlayOne(string aniName, string boolName, Action onStart,  Action onTrigger)
    {
        _aniName = aniName;
        _onTrigger = onTrigger;
        onStart();
        _animator.SetBool(boolName, true);
        IsPlay = true;
    }
    /// 
    /// 打开动画
    /// 
    /// 
    public void PlayLoop(string boolName)
    {
        _animator.SetBool(boolName, true);
    }
    /// 
    /// 关闭动画
    /// 
    /// 
    public void Stop(string boolName)
    {
        _animator.SetBool(boolName, false);
    }
    /// 
    /// 设置动画层
    /// 
    /// 
    /// 
    public void SetLayerWeight(string name,float num)
    {
        _animator.SetLayerWeight(_animator.GetLayerIndex(name), num);
    }
}

你可能感兴趣的:(Unity)