Unity3d,用代码动态添加动画事件

128 篇文章 1 订阅
64 篇文章 1 订阅
  1. //绑定到宿主身上
  2. public class AAAA : MonoBehaviour {
  3.     private Animator animator;//animator组件
  4.     public AnimationClip[] clips;//动画片段
  5.     
  6.     void Start() {
  7.         animator = GetComponent<Animator>();
  8.         clips = animator.runtimeAnimatorController.animationClips;
  9.         string a = "attack";//动画名
  10.         string b = "attack2";
  11.         for (int i = 0; i <clips.Length; i++)
  12.         {
  13.             if (clips[i].name==a)
  14.             {                                   //动画状态机,动画名,绑定的方法,绑定到动画的中间                    
  15.                 AddAnimationEvent(animator,a,"Hello",clips[i].length*0.5f);//添加动画事件
  16.             }
  17.             if (clips[i].name==b)
  18.             {                                                                    //0.8*24所在的位置 
  19.                 AddAnimationEvent(animator,b, "Attack", 0.8f);
  20.             }
  21.         }
  22.         
  23.     }
  24.     /// <summary>
  25.     /// 给动画添加动画事件
  26.     /// </summary>
  27.     /// <param name="ani"></param>//Animator组件
  28.     /// <param name="name"></param>//动画名字
  29.     /// <param name="fun"></param>//绑定的方法
  30.     /// <param name="time"></param>//绑定到那一帧
  31.     private void AddAnimationEvent(Animator ani, string name, string fun, float time)
  32.     {
  33.         AnimationClip[] temp = ani.runtimeAnimatorController.animationClips;
  34.         for (int i = 0; i < temp.Length; i++)
  35.         {
  36.             if (temp[i].name==name)
  37.             {
  38.                 AnimationEvent _event = new AnimationEvent();
  39.                 _event.functionName = fun;
  40.                 _event.time = time;
  41.                 temp[i].AddEvent(_event);
  42.                 break;
  43.             }
  44.         }
  45.         //重新绑定
  46.         ani.Rebind();
  47.     }
  48.     void Update() {
  49.     }
  50. //动画a绑定的方法
  51.     public void Hello() {
  52.         Debug.LogError("hello"+"-------------------");
  53.     }
  54. //动画b绑定的方法
  55.     public void Attack()
  56.     {
  57.         HelloAttack("helloAttack");
  58.     }
  59.     void HelloAttack(string str)
  60.     {
  61.         Debug.LogError("攻击攻击攻击" + str);
  62.     }
  63.     void OnDestory() {
  64.         CleanAllEvent();
  65.     }
  66.     /// <summary>
  67.     /// 清除动画事件
  68.     /// </summary>
  69.     private void CleanAllEvent()
  70.     {
  71.         for (int i = 0; i <clips.Length; i++)
  72.         {
  73.             clips[i].events = default(AnimationEvent[]);
  74.         }
  75.     }
  76. }
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值