StrobeLight.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. /// <summary>
  5. /// Flashes the attached light repetitively by alternating its intensity by 0 and its starting intensity.
  6. /// </summary>
  7. public class StrobeLight : MonoBehaviour
  8. {
  9. /// <summary>
  10. /// Gets added to the time before the first flash. Use to synchromize with music.
  11. /// </summary>
  12. [Tooltip("Gets added to the time before the first flash. Use to synchromize with music. ")]
  13. public float startDelay = 0f;
  14. /// <summary>
  15. /// Time between the start of each flash. Independent of the actual flash duration.
  16. /// </summary>
  17. [Tooltip("Time between the start of each flash. Independent of the actual flash duration. ")]
  18. public float secondsBetweenFlashes = 0.25f;
  19. /// <summary>
  20. /// How long each flash lasts/stays in the On state.
  21. /// </summary>
  22. [Tooltip("How long each flash lasts/stays in the On state. ")]
  23. public float flashDurationInSeconds = 0.1f;
  24. /// <summary>
  25. /// How long in seconds since the last flash.
  26. /// Gets incremented by Time.deltaTime in Update(). Starts a flash and resets when it hits secondsBetweenFlashes.
  27. /// </summary>
  28. private float flashtimer;
  29. /// <summary>
  30. /// The Light attached to this object.
  31. /// </summary>
  32. private Light lightcomponent;
  33. /// <summary>
  34. /// Cache for the starting intensity, which will be the flash intensity.
  35. /// </summary>
  36. private float maxintensity;
  37. // Use this for initialization
  38. void Start ()
  39. {
  40. lightcomponent = GetComponent<Light>();
  41. maxintensity = lightcomponent.intensity; //Cache the light's intensity.
  42. lightcomponent.intensity = 0;
  43. flashtimer = -startDelay; //Add the start delay.
  44. }
  45. // Update is called once per frame
  46. void Update ()
  47. {
  48. flashtimer += Time.deltaTime;
  49. if(flashtimer >= secondsBetweenFlashes) //Let there be light.
  50. {
  51. StartCoroutine(FlashLight());
  52. flashtimer = flashtimer % secondsBetweenFlashes;
  53. }
  54. }
  55. /// <summary>
  56. /// Turns on the light, waits for flashDurationInSeconds, then turns it off.
  57. /// </summary>
  58. /// <returns></returns>
  59. private IEnumerator FlashLight()
  60. {
  61. lightcomponent.intensity = maxintensity; //Set the light to be as bright as it started.
  62. for(float t = 0; t < flashDurationInSeconds; t += Time.deltaTime)
  63. {
  64. yield return null;
  65. }
  66. lightcomponent.intensity = 0;
  67. }
  68. }