AnimationPlayer.cs 2.4 KB

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