AnimationPlayer.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using UnityEngine;
  2. /* 自定义动画播放器 */
  3. public class AnimationPlayer : MonoBehaviour
  4. {
  5. public float speed = 1.0f;
  6. Animation animationMain;
  7. AnimationClip[] _animationClips;
  8. AnimationClip[] animationClips
  9. {
  10. get {
  11. if (this.animationMain == null) {
  12. this.animationMain = this.GetComponent<Animation>();
  13. }
  14. if (this._animationClips == null) {
  15. this._animationClips = new AnimationClip[this.animationMain.GetClipCount()];
  16. int i = 0;
  17. foreach (AnimationState AS in this.animationMain) {
  18. AS.speed = this.speed;
  19. this._animationClips[i] = this.animationMain.GetClip(AS.name);
  20. i++;
  21. }
  22. }
  23. return this._animationClips;
  24. }
  25. }
  26. WrapMode _wrapMode = WrapMode.Default;
  27. int _index = 0;
  28. bool _playing = false;
  29. float _playingTime = 0;
  30. float _animationTime = 0;
  31. string _animationName = "";
  32. int _completeCount = 0;
  33. public System.Action<AnimationPlayerCompleteResult> completeCallback;
  34. public void play(int index, WrapMode wrapMode = WrapMode.Default) {
  35. this._wrapMode = wrapMode;
  36. this._index = index;
  37. this._playing = true;
  38. this._playingTime = 0;
  39. this._completeCount = 0;
  40. this._animationTime = this.animationClips[index].length / this.speed;
  41. this._animationName = this.animationClips[index].name;
  42. this.animationClips[index].wrapMode = wrapMode;
  43. this.animationMain.CrossFade(this._animationName);
  44. }
  45. void Update()
  46. {
  47. if (this._playing) {
  48. this._playingTime += Time.deltaTime;
  49. int completeCount = (int) (this._playingTime / this._animationTime);
  50. if (completeCount > this._completeCount) {
  51. this._completeCount++;
  52. if (this._wrapMode != WrapMode.Loop) {
  53. this._playing = false;
  54. }
  55. if (this.completeCallback != null) {
  56. AnimationPlayerCompleteResult res = new AnimationPlayerCompleteResult();
  57. res.index = this._index;
  58. res.animationName = this._animationName;
  59. res.completeCount = this._completeCount;
  60. completeCallback(res);
  61. }
  62. }
  63. }
  64. }
  65. }
  66. public class AnimationPlayerCompleteResult {
  67. public int index = 0;
  68. public string animationName = "";
  69. public int completeCount = 0;
  70. }