#64 - Flicker script for Light in Unity
Date: 2019-06-08 12:00 - c#
Unity script for flicker light with custom parameters.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Light))]
public class FireFlicker : MonoBehaviour {
public float MaxReduction = 0.2f;
public float MaxIncrease = 0.2f;
public float RateDamping = 0.1f;
public float Strength = 300;
public bool StopFlickering;
private Light _lightSource;
private float _baseIntensity;
private bool _flickering;
private float _targetIntensity;
private Vector3 _basePosition;
private Vector3 _targetPosition;
public void Start() {
_lightSource = GetComponent<Light>();
_baseIntensity = _lightSource.intensity;
_basePosition = transform.position;
StartCoroutine(DoFlicker());
}
void Update() {
if (!StopFlickering && !_flickering) {
StartCoroutine(DoFlicker());
}
if (_flickering) {
_lightSource.intensity = Mathf.Lerp(_lightSource.intensity, _targetIntensity, Strength * Time.deltaTime);
transform.position = Vector3.Lerp(transform.position, _targetPosition, Time.deltaTime);
}
}
private IEnumerator DoFlicker() {
_flickering = true;
while (!StopFlickering) {
_targetIntensity = Random.Range(_baseIntensity - MaxReduction, _baseIntensity + MaxIncrease);
_targetPosition = _basePosition + RandomVector() * 0.02f;
yield return new WaitForSeconds(RateDamping);
}
_flickering = false;
}
private Vector3 RandomVector() {
return new Vector3(Random.Range(-1.0f, 1.0f), Random.Range(-1.0f, 1.0f), Random.Range(-1.0f, 1.0f)).normalized;
}
}