using UnityEngine; /* 自定义动画播放器 */ public class AnimationPlayer : MonoBehaviour { public float speed = 1.0f; Animation animationMain; AnimationClip[] _animationClips; AnimationClip[] animationClips { get { if (this.animationMain == null) { this.animationMain = this.GetComponent(); } if (this._animationClips == null) { this._animationClips = new AnimationClip[this.animationMain.GetClipCount()]; int i = 0; foreach (AnimationState AS in this.animationMain) { AS.speed = this.speed; this._animationClips[i] = this.animationMain.GetClip(AS.name); i++; } } return this._animationClips; } } WrapMode _wrapMode = WrapMode.Default; int _index = 0; bool _playing = false; float _playingTime = 0; float _animationTime = 0; string _animationName = ""; int _completeCount = 0; public System.Action completeCallback; public void play(int index, WrapMode wrapMode = WrapMode.Default) { Resume(); this._wrapMode = wrapMode; this._index = index; this._playing = true; this._playingTime = 0; this._completeCount = 0; this._animationTime = this.animationClips[index].length / this.speed; this._animationName = this.animationClips[index].name; this.animationMain[this._animationName].wrapMode = wrapMode; this.animationMain[this._animationName].speed = this.speed; this.animationMain.CrossFade(this._animationName); } void Update() { if (this._playing && !_pausing) { this._playingTime += Time.deltaTime; int completeCount = (int) (this._playingTime / this._animationTime); if (completeCount > this._completeCount) { this._completeCount++; if (this._wrapMode != WrapMode.Loop) { this._playing = false; } if (this.completeCallback != null) { AnimationPlayerCompleteResult res = new AnimationPlayerCompleteResult(); res.index = this._index; res.animationName = this._animationName; res.completeCount = this._completeCount; completeCallback(res); } } } } private float animationPauseTime; private bool _pausing = false; //暂停 public void Pause() { if (_pausing) return; _pausing = true; if (_playing) { _playing = false; AnimationState aniState = animationMain[_animationName]; if (aniState) { animationPauseTime = aniState.time; animationMain.Stop(_animationName); } } } //恢复 public void Resume() { if (_pausing) { _pausing = false; _playing = true; AnimationState aniState = animationMain[_animationName]; if (aniState) { aniState.time = animationPauseTime; animationMain.Play(_animationName); } } } public void StopAnimation(int index) { string name = this.animationClips[index].name; animationMain.Stop(name); } } public class AnimationPlayerCompleteResult { public int index = 0; public string animationName = ""; public int completeCount = 0; }