Skip to content

Instantly share code, notes, and snippets.

@VeggieVampire
Created August 19, 2019 07:47
Show Gist options
  • Save VeggieVampire/ea4cc2d07534f947bdad9284809856fc to your computer and use it in GitHub Desktop.
Save VeggieVampire/ea4cc2d07534f947bdad9284809856fc to your computer and use it in GitHub Desktop.
Flickering light script in unity 3D.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FlickeringLightScript : MonoBehaviour {
Light testLight;
public float minFlickerTime = 0.1f;
public float maxFlickerTime = 0.04f;
public float LightIntensity = 20f;
// Use this for initialization
void Start () {
testLight = GetComponent<Light> ();
StartCoroutine (Flashing ());
}
// Update is called once per frame
void Update () {
}
IEnumerator Flashing(){
while (true) {
yield return new WaitForSeconds (Random.Range(minFlickerTime,maxFlickerTime));
testLight.intensity = Random.Range(minFlickerTime,maxFlickerTime) * LightIntensity;
testLight.enabled = !testLight.enabled;
}
}
}
@Kiranix
Copy link

Kiranix commented Jul 29, 2022

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FlickerLight : MonoBehaviour
{
	Light myLight;

	float maxIntensity = 80.0f;
	float minIntensity = 20.0f;

	void Start()
	{
		myLight = GetComponent<Light>();
		StartCoroutine(Flicker());
	}

	IEnumerator Flicker()
	{

		float t = 0.0f;
		float duration = Random.Range(0.06f, 0.3f);
		float currIntensity = myLight.intensity;
		float targetIntensity = (currIntensity > 50.0f) ? minIntensity : maxIntensity;
		float variation = Random.Range(-20.0f, 20.0f);
		targetIntensity += variation;

		while (t < duration)
                {
			myLight.intensity = Mathf.Lerp(currIntensity, targetIntensity, t / duration);
			t += Time.deltaTime;
			yield return null;
                }

		StartCoroutine(Flicker());
	}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment