- //绑定到宿主身上
- public class AAAA : MonoBehaviour {
- private Animator animator;//animator组件
- public AnimationClip[] clips;//动画片段
-
- void Start() {
- animator = GetComponent<Animator>();
- clips = animator.runtimeAnimatorController.animationClips;
- string a = "attack";//动画名
- string b = "attack2";
- for (int i = 0; i <clips.Length; i++)
- {
- if (clips[i].name==a)
- { //动画状态机,动画名,绑定的方法,绑定到动画的中间
- AddAnimationEvent(animator,a,"Hello",clips[i].length*0.5f);//添加动画事件
- }
- if (clips[i].name==b)
- { //0.8*24所在的位置
- AddAnimationEvent(animator,b, "Attack", 0.8f);
- }
- }
-
- }
- /// <summary>
- /// 给动画添加动画事件
- /// </summary>
- /// <param name="ani"></param>//Animator组件
- /// <param name="name"></param>//动画名字
- /// <param name="fun"></param>//绑定的方法
- /// <param name="time"></param>//绑定到那一帧
- private void AddAnimationEvent(Animator ani, string name, string fun, float time)
- {
- AnimationClip[] temp = ani.runtimeAnimatorController.animationClips;
- for (int i = 0; i < temp.Length; i++)
- {
- if (temp[i].name==name)
- {
- AnimationEvent _event = new AnimationEvent();
- _event.functionName = fun;
- _event.time = time;
- temp[i].AddEvent(_event);
- break;
- }
- }
- //重新绑定
- ani.Rebind();
- }
- void Update() {
- }
- //动画a绑定的方法
- public void Hello() {
- Debug.LogError("hello"+"-------------------");
- }
- //动画b绑定的方法
- public void Attack()
- {
- HelloAttack("helloAttack");
- }
- void HelloAttack(string str)
- {
- Debug.LogError("攻击攻击攻击" + str);
- }
- void OnDestory() {
- CleanAllEvent();
- }
- /// <summary>
- /// 清除动画事件
- /// </summary>
- private void CleanAllEvent()
- {
- for (int i = 0; i <clips.Length; i++)
- {
- clips[i].events = default(AnimationEvent[]);
- }
- }
- }