I’m trying to make some random flickering in my lights, but give myself the ability to perhaps control when and how long it will flicker for. As such I have created a coroutine to make the light flicker, then a second coroutine that will fire that one but stop it after a given duration, which I am then testing by firing in Start. Using debugging is showing me the StopCoroutine is being called, yet the light still continues to flicker even after. Does anyone have any input on what I may have done wrong?
This is my code, currently:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LightFlicker : MonoBehaviour
{
private Light myLight;
[SerializeField]
public float minDur = .5f;
[SerializeField]
public float maxDur = 3.0f;
void Start()
{
myLight = this.gameObject.GetComponent<Light>();
StartCoroutine(FlickerLightForDuration(4.0f));
}
public IEnumerator FlickeringLight()
{
float elapsedTime = 0f;
float randomDur = Random.Range(minDur, maxDur);
while (elapsedTime < randomDur)
{
myLight.enabled = false;
yield return new WaitForSeconds(.05f);
myLight.enabled = true;
elapsedTime += Time.deltaTime;
yield return null;
}//end while time<duration
}//end FlickeringLight
public IEnumerator FlickerLightForDuration(float duration)
{
StartCoroutine(FlickeringLight());
yield return new WaitForSeconds(duration);
StopCoroutine(FlickeringLight());
}//end FlickerLightForDuration
}//end LightFlicker.cs