CausticAnimator.cs 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. namespace CalmWater
  5. {
  6. [RequireComponent(typeof(Projector))]
  7. public class CausticAnimator : MonoBehaviour
  8. {
  9. [SerializeField]
  10. private float _frameDuration = 0.1f;
  11. [SerializeField]
  12. private Texture2D[] _causticFrames = null;
  13. private Projector _projector;
  14. private Material _mat;
  15. private WaitForSeconds _delay;
  16. private int _propID;
  17. private int _currentFrame = 0;
  18. void OnEnable()
  19. {
  20. if (_causticFrames.Length < 2)
  21. {
  22. enabled = false;
  23. }
  24. if (_projector == null)
  25. {
  26. _projector = GetComponent<Projector> ();
  27. }
  28. if (_mat == null)
  29. {
  30. _mat = _projector.material;
  31. }
  32. _currentFrame = 0;
  33. _propID = Shader.PropertyToID ("_CausticTex");
  34. _delay = new WaitForSeconds (_frameDuration);
  35. }
  36. void OnDisabled()
  37. {
  38. StopCoroutine (AnimateCaustic ());
  39. }
  40. void Awake()
  41. {
  42. StartCoroutine (AnimateCaustic());
  43. }
  44. private int NextFrame()
  45. {
  46. _currentFrame ++;
  47. _currentFrame = _currentFrame >= _causticFrames.Length ? 0 : _currentFrame;
  48. return _currentFrame;
  49. }
  50. IEnumerator AnimateCaustic()
  51. {
  52. while (true)
  53. {
  54. yield return _delay;
  55. _mat.SetTexture (_propID, _causticFrames[NextFrame ()]);
  56. }
  57. }
  58. }
  59. }