标签:clip zed lse new oat static public ret frame
在用Unity自带的Animation组件的过程中,发现很多常见的基本功能并找不到,很大程度上影响了开发者正常使用,下面写一些扩展方法来进行补充:
1.得到当前Animation正在播放的动画
吐槽:为啥只有Animator可以直接取得,Animation却不行不愉快
1 public static string GetCurrentPlayingAnimationName(this Animation animation) 2 { 3 foreach (AnimationState state in animation) 4 { 5 if (animation.IsPlaying(state.name)) 6 return state.name; 7 } 8 return null; 9 }
2.得到一段AnimationClip的帧数
吐槽:这么基础的功能还要自己计算哎
1 public static float GetAnimationClipTotalFrame(this AnimationClip clip) 2 { 3 return clip.length / (1 / clip.frameRate); 4 }
这里也可以转为整型来使用
3.按一定的速率来执行播放指定动画
1 public static void PlayAnimationWithSpeed(this Animation animation, string animationName, float speed) 2 { 3 animation[animationName].speed = speed; 4 animation.CrossFade(animationName); 5 }
4.得到动画播放片段当前帧
吐槽:这个主要用于做动画事件,官方那个AnimationEvent的功能着实感觉鸡肋
1 public static int GetAnimationCurrentFrame(this Animation animation) 2 { 3 var animationName = GetCurrentPlayingAnimationName(animation); 4 if (animationName != null) 5 { 6 var currentTime = animation[animationName].normalizedTime; 7 float totalFrame = animation[animationName].clip.GetAnimationClipTotalFrame(); 8 return (int)(Mathf.Floor(totalFrame * currentTime) % totalFrame); 9 } 10 return -1; 11 }
5.当前动画暂停和恢复播放
吐槽:为啥连这个也没有啊,而且很坑的是如果记录自带的AnimationState后只要动画停止了AnimationState也跟着复位了,所幸还是自己新建一个类吧
1 public class AnimationStateInfo 2 { 3 public string name; 4 public float time; 5 public float speed; 6 7 public AnimationStateInfo(string name,float time,float speed) 8 { 9 this.name = name; 10 this.time = time; 11 this.speed = speed; 12 } 13 }
1 public static AnimationStateInfo Pause(this Animation animation) 2 { 3 var animationName = GetCurrentPlayingAnimationName(animation); 4 if (animationName != null) 5 { 6 var time = animation[animationName].time; 7 var speed = animation[animationName].speed; 8 var state = new AnimationStateInfo(animationName, time, speed); 9 animation.Stop(animationName); 10 return state; 11 } 12 return null; 13 }
1 public static void ResumePlay(this Animation animation, string name, float speed = 1f, AnimationStateInfo state = null) 2 { 3 if (state != null && name == state.name) 4 { 5 var animationName = state.name; 6 animation[animationName].time = state.time; 7 animation[animationName].speed = state.speed; 8 animation.Play(animationName); 9 } 10 else 11 { 12 animation.PlayAnimationWithSpeed(name, speed); 13 } 14 }
有种Animation快要被遗弃的感觉Orz
标签:clip zed lse new oat static public ret frame
原文地址:https://www.cnblogs.com/koshio0219/p/13161922.html