License: CC0 Public Domain ///. /// Component which will flicker a linked light while active. Oct 05, 2014 Finn Morgan is raising funds for Sprite Lamp - Dynamic lighting for 2D art on Kickstarter! Sprite Lamp is a tool to help game developers combine 2D.
| usingUnityEngine; |
| usingSystem.Collections.Generic; |
| // Written by Steve Streeting 2017 |
| // License: CC0 Public Domain http://creativecommons.org/publicdomain/zero/1.0/ |
| /// <summary> |
| /// Component which will flicker a linked light while active by changing its |
| /// intensity between the min and max values given. The flickering can be |
| /// sharp or smoothed depending on the value of the smoothing parameter. |
| /// |
| /// Just activate / deactivate this component as usual to pause / resume flicker |
| /// </summary> |
| publicclassLightFlickerEffect : MonoBehaviour { |
| [Tooltip('External light to flicker; you can leave this null if you attach script to a light')] |
| publicnewLightlight; |
| [Tooltip('Minimum random light intensity')] |
| publicfloatminIntensity=0f; |
| [Tooltip('Maximum random light intensity')] |
| publicfloatmaxIntensity=1f; |
| [Tooltip('How much to smooth out the randomness; lower values = sparks, higher = lantern')] |
| [Range(1, 50)] |
| publicintsmoothing=5; |
| // Continuous average calculation via FIFO queue |
| // Saves us iterating every time we update, we just change by the delta |
| Queue<float> smoothQueue; |
| floatlastSum=0; |
| /// <summary> |
| /// Reset the randomness and start again. You usually don't need to call |
| /// this, deactivating/reactivating is usually fine but if you want a strict |
| /// restart you can do. |
| /// </summary> |
| publicvoidReset() { |
| smoothQueue.Clear(); |
| lastSum=0; |
| } |
| voidStart() { |
| smoothQueue=newQueue<float>(smoothing); |
| // External or internal light? |
| if (lightnull) { |
| light=GetComponent<Light>(); |
| } |
| } |
| voidUpdate() { |
| if (lightnull) |
| return; |
| // pop off an item if too big |
| while (smoothQueue.Count>=smoothing) { |
| lastSum-=smoothQueue.Dequeue(); |
| } |
| // Generate random new item, calculate new average |
| floatnewVal=Random.Range(minIntensity, maxIntensity); |
| smoothQueue.Enqueue(newVal); |
| lastSum+=newVal; |
| // Calculate new smoothed average |
| light.intensity=lastSum/ (float)smoothQueue.Count; |
| } |
| } |
commented May 20, 2019
Thanks, Steve. Perfectly implemented! |
commented Jun 25, 2019
Mind if I add slight movement to the light itself to add even more realism? |
commented Jun 26, 2019

Feel free to fork it to do whatever you want :) |