- Home /
Question by
hellobobandgeorge · Aug 24, 2020 at 10:59 AM ·
lightingfunction
Flicker Script Not Working
I am working on a 3D game. I have implemented a script to cause the two directional lights I have in the scene to flicker. I have the max intensity set to 3, and the min is 2. However, sometimes the light just shuts off completely! Can anybody help me figure out why the light is shutting off? I'm using Unity 5.6.7f1 32-bit because it is the newest 32-bit version I'm aware off. Anyways, here's the code: using System.Collections.Generic; using UnityEngine;
public class flicker : MonoBehaviour {
[Tooltip("External light to flicker; you can leave this null if you attach script to a light")]
public new Light light;
[Tooltip("Minimum random light intensity")]
public float minIntensity = 0f;
[Tooltip("Maximum random light intensity")]
public float maxIntensity = 1f;
[Tooltip("How much to smooth out the randomness; lower values = sparks, higher = lantern")]
[Range(1, 50)]
public int smoothing = 5;
// Continuous average calculation via FIFO queue
// Saves us iterating every time we update, we just change by the delta
Queue<float> smoothQueue;
float lastSum = 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>
public void Reset() {
smoothQueue.Clear();
lastSum = 0;
}
void Start() {
smoothQueue = new Queue<float>(smoothing);
// External or internal light?
if (light == null) {
light = GetComponent<Light>();
}
}
void Update() {
if (light == null)
return;
// pop off an item if too big
while (smoothQueue.Count >= smoothing) {
lastSum -= smoothQueue.Dequeue();
}
// Generate random new item, calculate new average
float newVal = Random.Range(minIntensity, maxIntensity);
smoothQueue.Enqueue(newVal);
lastSum += newVal;
// Calculate new smoothed average
light.intensity = lastSum / (float)smoothQueue.Count;
}
}
Comment
Your answer
Follow this Question
Related Questions
Activating function in distant item 0 Answers
Use Render Setting's ambient light in shader 0 Answers
Simple static function to display text onscreen (Accessible from anywhere) 1 Answer
Linear Lighting has LOD?> 0 Answers
Weapon Shake 2 Answers