AnimationPlayer.cs 2.5 KB

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