SpriteSheetIndexV.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. using UnityEngine;
  2. using System.Collections;
  3. public class SpriteSheetIndexV : MonoBehaviour
  4. {
  5. public float repeatX = 1;
  6. public int uvTieY = 1;
  7. public int index = 0;
  8. public bool enable = false;
  9. public float[] times;
  10. public int[] frames;
  11. public float length;
  12. public bool loop;
  13. private Vector2 _size;
  14. private Renderer _myRenderer;
  15. private int _lastIndex = -1;
  16. private float _framecount;
  17. void Start()
  18. {
  19. _size = new Vector2(repeatX, 1.0f / uvTieY);
  20. _myRenderer = GetComponent<Renderer>();
  21. if (_myRenderer == null)
  22. enabled = false;
  23. _framecount = 0;
  24. Update();
  25. }
  26. // Update is called once per frame
  27. void Update()
  28. {
  29. UpdateAnimation();
  30. _myRenderer.enabled = enable;
  31. if(!enable)
  32. {
  33. return;
  34. }
  35. // Calculate index
  36. if (index != _lastIndex)
  37. {
  38. // split into horizontal and vertical index
  39. int uIndex = 0;
  40. int vIndex = index % uvTieY;
  41. // build offset
  42. // v coordinate is the bottom of the image in opengl so we need to invert.
  43. Vector2 offset = new Vector2(uIndex * uvTieY, 1.0f - _size.y - vIndex * _size.y);
  44. _myRenderer.material.SetTextureOffset("_MainTex", offset);
  45. _myRenderer.material.SetTextureScale("_MainTex", _size);
  46. _lastIndex = index;
  47. }
  48. }
  49. void UpdateAnimation()
  50. {
  51. if (times.Length == 0) return;
  52. if (!loop && _framecount > length) return;
  53. _framecount += Time.deltaTime;
  54. _size = new Vector2(repeatX, 1.0f / uvTieY);
  55. if (_framecount > length)
  56. {
  57. _framecount -= length;
  58. }
  59. if (_framecount < 0 && loop)
  60. {
  61. _framecount = 0;
  62. }
  63. for (int i = times.Length-1; i >= 0; --i)
  64. {
  65. if(_framecount >= times[i])
  66. {
  67. if (frames[i] < 0)
  68. {
  69. enable = false;
  70. }
  71. else
  72. {
  73. enable = true;
  74. index = frames[i];
  75. }
  76. return;
  77. }
  78. }
  79. }
  80. public void SetIndex(int i)
  81. {
  82. index = (int)i;
  83. }
  84. public void SetRepeat(float r)
  85. {
  86. repeatX = r;
  87. }
  88. }