Animator工具函数收集
1) 获取AnimationClip
public static bool TryGetAnimatorClip(Animator animator, string clipName, out AnimationClip outClip) { var clips = animator.runtimeAnimatorController.animationClips; for (var i = 0; i < clips.Length; ++i) { var clip = clips[i]; if (clip.name == clipName) { outClip = clip; return true; } } outClip = null; return false; }
2) 另一种获取AnimationClip
public static bool TryGetAnimatorClip(Animator animator, int layerIndex, string clipName, out AnimationClip outClip) { var clipInfo = animator.GetCurrentAnimatorClipInfo(layerIndex); for (var i = 0; i < clipInfo.Length; ++i) { var clip = clipInfo[i].clip; if (clip.name == clipName) { outClip = clip; return true; } } outClip = null; return false; }
3) 状态切换
public static void ForceCrossFade(Animator animator, string name, float transitionDuration, int layer = 0, float normalizedTime = float.NegativeInfinity) { if (animator.GetNextAnimatorStateInfo(layer).fullPathHash == 0) { animator.CrossFade(name, transitionDuration, layer, normalizedTime); } else { animator.Play(animator.GetNextAnimatorStateInfo(layer).fullPathHash, layer); animator.Update(0); animator.CrossFade(name, transitionDuration, layer, normalizedTime); } }
4) 状态机中是否有某个状态
public static bool HasState(Animator animator, string stateName, int layerIndex = 0) { var stateId = Animator.StringToHash(stateName); return animator.HasState(layerIndex, stateId); }